I'm using minSDK = 8 and targetSDK = 17
At activity start, my 3 screens (3 different Views) are set to invisible in the XML layout. In onResume, I call setScreen(1), which starts an animation that sets View 'wait' to visible. However, at line 34 where 'wait' is set to visible, nothing happens. If I remove the comment // from line 43 where 'main' is set to invisible, 'wait' becomes visible.
Why does 'wait' not appear when line 43 is commented out? Why does it take setting the already invisible 'main' View to invisible for 'wait' to appear?
public class TestActivity extends Activity {
static final String TAG = "test";
public Context context;
Activity myActivity;
UserFunctions userFunctions;
Button but_begin;
int status;
View main;
View wait;
View noconnect;
Animation fadeIntoWait;
Animation fadeIntoConnect;
Animation fadeIntoMain;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.test);
context = getApplicationContext();
myActivity = this;
main = findViewById(R.id.screen_main);
wait = findViewById(R.id.screen_wait);
noconnect = findViewById(R.id.screen_connect);
fadeIntoWait = AnimationUtils.loadAnimation(this, R.anim.fade_in);
fadeIntoConnect = AnimationUtils.loadAnimation(this, R.anim.fade_in);
fadeIntoMain = AnimationUtils.loadAnimation(this, R.anim.fade_in);
fadeIntoWait.setAnimationListener(new AnimationListener() {
#Override
public void onAnimationStart(Animation animation) {
wait.setVisibility(View.VISIBLE);
}
#Override
public void onAnimationRepeat(Animation animation) {
}
#Override
public void onAnimationEnd(Animation animation) {
//main.setVisibility(View.INVISIBLE);
//noconnect.setVisibility(View.INVISIBLE);
}
});
fadeIntoConnect.setAnimationListener(new AnimationListener() {
#Override
public void onAnimationStart(Animation animation) {
noconnect.setVisibility(View.VISIBLE);
}
#Override
public void onAnimationRepeat(Animation animation) {
}
#Override
public void onAnimationEnd(Animation animation) {
wait.setVisibility(View.INVISIBLE);
}
});
fadeIntoMain.setAnimationListener(new AnimationListener() {
#Override
public void onAnimationStart(Animation animation) {
main.setVisibility(View.VISIBLE);
}
#Override
public void onAnimationRepeat(Animation animation) {
}
#Override
public void onAnimationEnd(Animation animation) {
wait.setVisibility(View.INVISIBLE);
}
});
}
#Override
public void onStart() {
super.onStart();
}
#Override
public void onResume() {
super.onResume();
setScreen(1);
}
public void setScreen(int screen) {
switch (screen) {
case 1: // into wait
wait.startAnimation(fadeIntoWait);
break;
case 2: // to noconnect
noconnect.startAnimation(fadeIntoConnect);
break;
case 3: // to main
main.startAnimation(fadeIntoMain);
break;
}
}
public void gotoActivity(Class<?> s) {
Intent g = new Intent(getApplicationContext(), s);
// Close all views before launching Dashboard
g.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(g);
overridePendingTransition(R.anim.fade_in, R.anim.fade_out);
}
public void retryConnect(View view) {
}
public void begin(View view) {
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
menu.add(0, 1, 0, "Exit App");
menu.add(0, 2, 0, "Close Menu");
menu.add(0, 3, 0, "Dashboard");
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case 1: // log out
closeOptionsMenu();
return true;
case 2: // Exit App
finish();
return true;
case 3: // Exit App
gotoActivity(DashboardActivity.class);
return true;
}
return super.onOptionsItemSelected(item);
}
public void menu(View v) {
openOptionsMenu();
}
}
Here is the XML:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent" >
<LinearLayout
android:id="#+id/header"
android:layout_width="match_parent"
android:layout_height="44dp"
android:layout_alignParentTop="true"
android:background="#drawable/line" >
</LinearLayout>
<FrameLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_below="#id/header" >
<RelativeLayout
android:id="#+id/screen_wait"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#000"
android:visibility="gone" >
<ImageView
android:id="#+id/img_wait"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_gravity="center"
android:contentDescription="#string/wait"
android:src="#drawable/wait"
/>
</RelativeLayout>
<RelativeLayout
android:id="#+id/screen_connect"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#000"
android:visibility="gone" >
<ImageView
android:id="#+id/img_connect"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_gravity="center"
android:contentDescription="#string/connect"
android:onClick="retryConnect"
android:src="#drawable/connect"
/>
</RelativeLayout>
<RelativeLayout
android:id="#+id/screen_main"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#000"
android:visibility="gone" >
<ScrollView
android:id="#+id/middle"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_above="#+id/footer"
android:background="#2F2430" >
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#2F2430" >
<TextView
android:id="#+id/textView3"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
<TextView
android:id="#+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:text="#string/idea"
android:textAppearance="?android:attr/textAppearanceMedium"
android:textColor="#21dbd4" />
<Button
android:id="#+id/but_begin"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/TextView01"
android:layout_centerHorizontal="true"
android:layout_marginTop="67dp"
android:onClick="begin"
android:text="Begin" />
</RelativeLayout>
</ScrollView>
<RelativeLayout
android:id="#+id/footer"
android:layout_width="match_parent"
android:layout_height="44dp"
android:layout_alignParentBottom="true"
android:background="#drawable/line"
android:orientation="vertical" >
<TextView
android:id="#+id/textView2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:text="Pennies:" />
<TextView
android:id="#+id/textView4"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_marginLeft="22dp"
android:layout_toRightOf="#+id/textView2" />
<Button
android:id="#+id/btnMenu"
style="?android:attr/buttonStyleSmall"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:onClick="menu"
android:text="Menu" />
</RelativeLayout>
</RelativeLayout>
</FrameLayout>
</RelativeLayout>
Your UI is not laid out until after onCreate(). Try moving the animations to onStart() or better, use a ViewTreeObserver to start them once layout is complete
Related
When i open this activity, drawer is already opened by default. When i try to close the drawer, it doesn't. In short drawer is malfunctioning. I have attached both XML code & JAVA code.
This is XML File Code:
<?xml version="1.0" encoding="utf-8"?>
<android.support.v4.widget.DrawerLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/drawer_layout"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:fitsSystemWindows="true"
tools:openDrawer="start">
<android.support.design.widget.CoordinatorLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#drawable/bg_home">
<include
android:id="#+id/action_bar"
layout="#layout/actionbar"
/>
<android.support.design.widget.NavigationView
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:layout_gravity="start"
android:id="#+id/nav_view"
app:headerLayout="#layout/navigation"
app:menu="#menu/drawer_menu"/>
<android.support.design.widget.FloatingActionButton
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="bottom|end"
android:layout_marginRight="20dp"
android:layout_marginBottom="210dp"
android:src="#drawable/add_to_cart"
android:elevation="6dp"
android:id="#+id/fab_place_order"
app:pressedTranslationZ="12dp"
app:backgroundTint="#color/fabOrder"
android:visibility="invisible"
/>
<android.support.design.widget.FloatingActionButton
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="bottom|end"
android:layout_marginRight="20dp"
android:layout_marginBottom="150dp"
android:src="#drawable/ic_account_balance_wallet_black_24dp"
android:elevation="6dp"
android:id="#+id/fab_balance"
app:pressedTranslationZ="12dp"
app:backgroundTint="#color/fabBalance"
android:visibility="invisible"
/>
<android.support.design.widget.FloatingActionButton
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="bottom|end"
android:layout_marginRight="20dp"
android:layout_marginBottom="90dp"
android:src="#drawable/ic_exit_to_app_black_24dp"
android:elevation="6dp"
android:id="#+id/fab_logout"
app:pressedTranslationZ="12dp"
app:backgroundTint="#color/fabExit"
android:visibility="invisible"
/>
<android.support.design.widget.FloatingActionButton
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="bottom|end"
android:layout_marginRight="20dp"
android:layout_marginBottom="20dp"
android:src="#drawable/menu"
android:elevation="6dp"
android:id="#+id/fab_menu"
app:pressedTranslationZ="12dp"
android:backgroundTint="#color/fabMain"
/>
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="match_parent">
<ProgressBar
android:id="#+id/progressBar"
style="?android:attr/progressBarStyle"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerInParent="true" />
<TextView
android:id="#+id/label1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_alignParentEnd="true"
android:layout_alignParentRight="true"
android:layout_marginBottom="230dp"
android:layout_marginEnd="80dp"
android:layout_marginRight="70dp"
android:text="Place Order"
android:textColor="#003200"
android:textStyle="bold"
android:visibility="invisible" />
<TextView
android:id="#+id/label2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignEnd="#+id/label1"
android:layout_alignLeft="#+id/label1"
android:layout_alignParentBottom="true"
android:layout_alignRight="#+id/label1"
android:layout_marginBottom="170dp"
android:text="Check Balance"
android:textColor="#000032"
android:textStyle="bold"
android:visibility="invisible" />
<TextView
android:id="#+id/label3"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignEnd="#+id/label1"
android:layout_alignParentBottom="true"
android:layout_alignRight="#+id/label1"
android:layout_marginBottom="110dp"
android:text="Logout"
android:textColor="#320000"
android:textStyle="bold"
android:visibility="invisible" />
</RelativeLayout>
</android.support.design.widget.CoordinatorLayout>
</android.support.v4.widget.DrawerLayout>
This is JAVA File Code:
public class HomeActivity extends AppCompatActivity {
ConnectionDetector connectionDetector = new ConnectionDetector(this);
DatabaseHelper helper = new DatabaseHelper(this);
Handler handler = new Handler();
FloatingActionButton fab_menu,fab_balance,fab_logout,fab_order;
Animation fabOpen,fabClose,fabClockwise,fabAnticlockwise;
boolean isOpen = false, status = false;
ProgressBar progressBar;
private boolean isUserClickedBackButton = false;
private DrawerLayout drawerLayout;
TextView t1,t2,t3;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_home);
helper.startFirebaseDB();
Toolbar toolbar = findViewById(R.id.action_bar);
toolbar.setTitleTextColor(getResources().getColor(R.color.white));
setSupportActionBar(toolbar);
drawerLayout = findViewById(R.id.drawer_layout);
ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(this,drawerLayout,toolbar,R.string.navigation_drawer_open,R.string.navigation_drawer_close);
toggle.syncState();
progressBar = findViewById(R.id.progressBar);
fab_menu = findViewById(R.id.fab_menu);
fab_menu.setEnabled(false);
fab_order = findViewById(R.id.fab_place_order);
fab_balance = findViewById(R.id.fab_balance);
fab_logout = findViewById(R.id.fab_logout);
t1 = findViewById(R.id.label1);
t2 = findViewById(R.id.label2);
t3 = findViewById(R.id.label3);
fabOpen= AnimationUtils.loadAnimation(getApplicationContext(),R.anim.fab_open);
fabClose= AnimationUtils.loadAnimation(getApplicationContext(),R.anim.fab_close);
fabClockwise= AnimationUtils.loadAnimation(getApplicationContext(),R.anim.rotate_clockwise);
fabAnticlockwise= AnimationUtils.loadAnimation(getApplicationContext(),R.anim.rotate_anticlockwise);
handler.postDelayed(new Runnable() {
#Override
public void run() {
progressBar.setVisibility(View.GONE);
fab_menu.setEnabled(true);
}
},2000);
fab_menu.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if(isOpen)
{
fab_order.startAnimation(fabClose);
fab_balance.startAnimation(fabClose);
fab_logout.startAnimation(fabClose);
fab_menu.startAnimation(fabAnticlockwise);
fab_balance.setClickable(false);
fab_logout.setClickable(false);
handler.postDelayed(new Runnable() {
#Override
public void run() {
t1.setVisibility(View.INVISIBLE);
t2.setVisibility(View.INVISIBLE);
t3.setVisibility(View.INVISIBLE);
}
},200);
isOpen = false;
}
else
{
fab_order.startAnimation(fabOpen);
fab_balance.startAnimation(fabOpen);
fab_logout.startAnimation(fabOpen);
fab_menu.startAnimation(fabClockwise);
fab_balance.setClickable(true);
fab_logout.setClickable(true);
isOpen = true;
handler.postDelayed(new Runnable() {
#Override
public void run() {
t1.setVisibility(View.VISIBLE);
t2.setVisibility(View.VISIBLE);
t3.setVisibility(View.VISIBLE);
}
},200);
}
}
});
fab_order.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
status = helper.checkUserStatus(helper.getUser());
if(!connectionDetector.isConnected()) {
Toast.makeText(HomeActivity.this, "Check your internet connection !!!", Toast.LENGTH_LONG).show();
return;
}
else if(!status) {
Toast t1 = Toast.makeText(HomeActivity.this, "Access Denied !!!", Toast.LENGTH_LONG);
Toast t2 = Toast.makeText(HomeActivity.this, "Please contact: Ayaz Handloom Store", Toast.LENGTH_LONG);
t1.setGravity(Gravity.CENTER,0,0);
t1.show();
t2.setGravity(Gravity.CENTER,0,0);
t2.show();
return;
}
else {
Intent newOrder = new Intent(HomeActivity.this, NewOrderActivity.class);
startActivity(newOrder);
finish();
}
}
});
fab_balance.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent balance = new Intent(HomeActivity.this,BalanceActivity.class);
startActivity(balance);
finish();
}
});
fab_logout.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent logout = new Intent(HomeActivity.this,MainActivity.class);
helper.logout();
Toast.makeText(HomeActivity.this, "Logout success !!!", Toast.LENGTH_LONG).show();
startActivity(logout);
finish();
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.menu,menu);
return super.onCreateOptionsMenu(menu);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch(item.getItemId())
{
case R.id.edit_profile:
break;
case R.id.change_password:
break;
case R.id.settings:
break;
case R.id.logout:
DialogInterface.OnClickListener dialogBox = new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
switch (which){
case DialogInterface.BUTTON_POSITIVE:
Intent logout = new Intent(HomeActivity.this,MainActivity.class);
helper.logout();
Toast.makeText(HomeActivity.this, "Logout success !!!", Toast.LENGTH_LONG).show();
startActivity(logout);
finish();
break;
case DialogInterface.BUTTON_NEGATIVE:
Toast cancel = Toast.makeText(HomeActivity.this, "Request cancelled !!!", Toast.LENGTH_SHORT);
cancel.setGravity(Gravity.CENTER,0,0);
cancel.show();
break;
}
}
};
AlertDialog.Builder builder = new AlertDialog.Builder(HomeActivity.this);
builder.setMessage("Are you sure to logout?").setPositiveButton("Yes", dialogBox).setNegativeButton("No", dialogBox).show();
break;
}
return super.onOptionsItemSelected(item);
}
#Override
public void onBackPressed() {
if (drawerLayout.isDrawerOpen(GravityCompat.START))
drawerLayout.closeDrawer(GravityCompat.START);
else {
if (!isUserClickedBackButton) {
Toast.makeText(this, "Press back key again for Main Page !!!", Toast.LENGTH_LONG).show();
isUserClickedBackButton = true;
handler.postDelayed(new Runnable() {
#Override
public void run() {
isUserClickedBackButton = false;
}
}, 3000);
} else {
Intent back = new Intent(HomeActivity.this, MainActivity.class);
startActivity(back);
finish();
}
}
}
}
If i delete XML code which is inside DrawerLayout, then it works fine.
you forgot to add drawerLayout.addDrawerListener(toggle); before toggle.syncState();
In my app I have to use navigation drawer with all activities. So I have created a base activity called DrawerActivity. I wrote the code for navigation drawer in DrawerActivity and then extended the UserDashBoardActivity from DrawerActivity.
The problem is that DrawerActivity properties aren't executed in UserDashBoardActivity. I can't interact with DrawerActivity in UserDashBoardActivity. Here that drawer menu is in ActionBar in all the activities.
This is my DrawerActivity
public class DrawerActivity extends ActionBarActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.drawer_list_view);
mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
mDrawerList = (ListView) findViewById(R.id.left_drawer);
mDrawerItems = getResources().getStringArray(R.array.navigation_drawer_items_array);
//mDrawerLayout.setDrawerShadow(R.drawable.drawer_shadow, GravityCompat.START);
mDrawerList.setAdapter(new ArrayAdapter<String>(
this, R.layout.drawer_list_items, mDrawerItems));
mDrawerList.setOnItemClickListener(new DrawerItemClickListener());
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setHomeButtonEnabled(true);
mDrawerToggle = new ActionBarDrawerToggle(this,
mDrawerLayout, R.drawable.ic_menu,
R.string.drawer_open, R.string.drawer_close) {
public void onDrawerOpened(View view) {
invalidateOptionsMenu();
}
public void onDrawerClosed(View view) {
invalidateOptionsMenu();
}
};
mDrawerLayout.setDrawerListener(mDrawerToggle);
}
#Override
protected void onPostCreate(Bundle savedInstanceState) {
super.onPostCreate(savedInstanceState);
mDrawerToggle.syncState();
}
#Override
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
mDrawerToggle.onConfigurationChanged(newConfig);
}
#Override
public boolean onPrepareOptionsMenu(Menu menu) {
boolean drawerOpen = mDrawerLayout.isDrawerOpen(mDrawerList);
for (int index = 0; index < menu.size(); index++) {
MenuItem menuItem = menu.getItem(index);
if (menuItem != null) {
// hide the menu items if the drawer is open
menuItem.setVisible(!drawerOpen);
}
}
return super.onPrepareOptionsMenu(menu);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
if (mDrawerToggle.onOptionsItemSelected(item)) {
return true;
}
return super.onOptionsItemSelected(item);
}
private class DrawerItemClickListener implements ListView.OnItemClickListener {
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int position, long id) {
switch (position) {
case 0: {
Intent intent = new Intent(DrawerActivity.this, UserDashBoardActivity.class);
startActivity(intent);
break;
}
case 1: {
Intent intent = new Intent(DrawerActivity.this, AdmissionActivity.class);
startActivity(intent);
break;
}
default:
break;
}
mDrawerLayout.closeDrawer(mDrawerList);
}
}
This is my UseDashBoardActivity
public class UserDashBoardActivity extends DrawerActivity {
private Context context;
private ImageButton searchBtn;
private ImageButton favBtn;
private ImageButton profileBtn;
private ImageButton reminderBtn;
private ImageButton logoutBtn;
private ImageButton notificationBtn;
private ImageView seatchIcon;
private DrawerLayout mDrawerLayout;
private ListView mDrawerList;
private ActionBarDrawerToggle mDrawerToggle;
// slide menu items
private String[] navMenuTitles;
private TypedArray navMenuIcons;
#Override
protected void onStart() {
super.onStart();
AppActivityStatus.setActivityStarted();
AppActivityStatus.setActivityContext(context);
}
#Override
protected void onPause() {
super.onPause();
AppActivityStatus.setActivityStoped();
}
#Override
protected void onResume() {
super.onResume();
AppActivityStatus.setActivityStarted();
}
#Override
protected void onStop() {
super.onStop();
AppActivityStatus.setActivityStoped();
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_user_dash_boad, menu);
return true;
}
// delete the selected event from event list added here
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.action_notify:
return true;
case R.id.action_favourite:
return true;
case R.id.action_navigation:
}
return super.onOptionsItemSelected(item);
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
getSupportActionBar().setCustomView(R.layout.action_bar_layout);
setContentView(R.layout.user_dash_board);
context = getApplicationContext();
searchBtn = (ImageButton) findViewById(R.id.search_btn);
favBtn = (ImageButton) findViewById(R.id.fav_btn);
profileBtn = (ImageButton) findViewById(R.id.profile_btn);
reminderBtn = (ImageButton) findViewById(R.id.reminder_btn);
notificationBtn = (ImageButton) findViewById(R.id.notification_btn);
logoutBtn = (ImageButton) findViewById((R.id.logout_btn));
final EditText Search = (EditText)findViewById(R.id.emailAddress);
mDrawerList = (ListView)findViewById(R.id.drawer_layout);
searchBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
Intent regAct = new Intent(getApplicationContext(), SearchActivity.class);
// Clears History of Activity
regAct.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(regAct);
}
});
favBtn.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View arg0){
Intent tabAct = new Intent(getApplicationContext(),TabHostActivity.class);
tabAct.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(tabAct);
}
});
profileBtn.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View arg0) {
Intent tabAct = new Intent(getApplicationContext(),AboutCollegeActivity.class);
tabAct.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(tabAct);
}
});
}
}
This is my actionbar xml
<?xml version="1.0" encoding="utf-8"?>
<menu
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:appmunu="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
tools:context="com.after2.svirtzone.after2_gradle.UserDashBoardActivity">
<item
android:id="#+id/action_notify"
android:icon="#drawable/mail_icon"
appmunu:showAsAction="always"
android:title="Notification" />
<item
android:id="#+id/action_favourite"
android:icon="#drawable/favourite_icon"
appmunu:showAsAction="always"
android:title="Favourite" />
<item
//this is the menu button for navigation drawer
android:id ="#+id/action_navigation"
android:icon="#drawable/ic_menu"
appmunu:showAsAction = "always"
android:title="navigation"
android:layout_gravity="left"/>
</menu>
This is the xml layout for navigationdrawer listview
<android.support.v4.widget.DrawerLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/drawer_layout"
android:layout_width="match_parent"
android:layout_height="match_parent">
<!-- The main content view -->
<FrameLayout
android:id="#+id/activity_frame"
android:layout_width="match_parent"
android:layout_height="match_parent" ></FrameLayout>
<!-- The navigation drawer -->
<ListView
android:id="#+id/left_drawer"
android:layout_width="240dp"
android:layout_height="match_parent"
android:layout_gravity="start"
android:background="#111"
android:choiceMode="singleChoice"
android:divider="#android:color/transparent"
android:dividerHeight="0dp" />
</android.support.v4.widget.DrawerLayout>
This layout is UserDashboard layout
?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_gravity="center"
android:background="#color/appblue"
android:orientation="vertical">
<EditText
android:id="#+id/emailAddress"
android:layout_width="fill_parent"
android:layout_height="100dp"
android:background="#drawable/edit_text_style"
android:gravity="center|start"
android:hint="#string/edittext_hint"
android:inputType="textEmailAddress"
android:maxLength="40"
android:textSize="18sp"
android:visibility="gone" />
<ImageView
android:id="#+id/search_icon_btn"
android:layout_width="wrap_content"
android:layout_height="80dp"
android:layout_marginLeft="580dp"
android:layout_marginRight="10dp"
android:layout_marginTop="-90dp"
android:padding="5dp"
android:src="#drawable/search_icon" />
<ImageButton
android:id="#+id/search_btn"
android:layout_width="250dp"
android:layout_height="250dp"
android:layout_gravity="center_horizontal"
android:layout_marginLeft="5dp"
android:layout_marginRight="210dp"
android:layout_marginTop="30dp"
android:background="#drawable/search_blue"
android:gravity="center" />
<TextView
android:id="#+id/searchCollege"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="80dp"
android:layout_marginRight="100dp"
android:layout_marginTop="20dp"
android:text="#string/search_college"
android:textColor="#color/green"
android:textSize="30sp" />
<ImageButton
android:id="#+id/fav_btn"
android:layout_width="250dp"
android:layout_height="250dp"
android:layout_gravity="center_horizontal"
android:layout_marginLeft="200dp"
android:layout_marginRight="5dp"
android:layout_marginTop="-305dp"
android:background="#drawable/fav_blue"
android:gravity="center" />
<TextView
android:id="#+id/myFavourites"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="500dp"
android:layout_marginRight="10dp"
android:layout_marginTop="20dp"
android:text="#string/my_favourites"
android:textColor="#color/green"
android:textSize="30sp" />
</LinearLayout>
The UserDashboard activity is executed as it is but I need the property of DrawerActivity to be executed along with this activity. How to do it?
Let the parent Activity add the required ViewGroup as child of the FrameLayout. To achieve this, use the following method for DrawerActivity:
protected void addToContentView(int layoutResID)
{
// as part of onCreate() we had already
// setContentView(R.layout.activity_drawer);
if (layoutResID >= 0)
{
Toast.makeText(this, "activity content found", Toast.LENGTH_LONG).show();
FrameLayout fl = (FrameLayout)findViewById(R.id.activity_frame);
View.inflate(this, layoutResID, fl);
}
else
{
Toast.makeText(this, "activity content missing", Toast.LENGTH_LONG).show();
}
}
Then, in the onCreate() method of the child Activity:
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
// call this instead of setContentView()
addToContentView(R.layout.activity_user_dashboard);
// put here your code as before...
}
Drawer's layout:
<?xml version="1.0" encoding="utf-8"?>
<android.support.v4.widget.DrawerLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:id="#+id/drawer_layout"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:fitsSystemWindows="true">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<android.support.v7.widget.Toolbar
android:id="#+id/toolbar"
android:layout_width="match_parent"
android:layout_height="?attr/actionBarSize"
android:background="?attr/colorPrimary"
app:popupTheme="#style/ThemeOverlay.AppCompat.Light"
app:theme="#style/ThemeOverlay.AppCompat.Dark.ActionBar"
/>
<!--you need to add everything to this frameLayout then only you will be able to access Navigation DrawerLayout-->
<FrameLayout
android:id="#+id/fragment"
android:layout_width="match_parent"
android:layout_height="match_parent"></FrameLayout>
</LinearLayout>
<ListView
android:id="#+id/navigation_list"
android:layout_width="320dp"
android:layout_height="match_parent"
android:layout_gravity="start"
android:divider="#android:color/transparent"
android:dividerHeight="0dp"
android:fitsSystemWindows="true"
android:background="#color/white"
/>
</android.support.v4.widget.DrawerLayout>
The Activity with Drawer:(Only important code is shown)
public abstract class BaseDrawerLayoutActivity extends AppCompatActivity implements OnItemClickListener {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.base_drawer_layout_activity);
//rest of the things
//NOTE: loadNavMenu is abstract so that you can implement it in other activities as per you need, otherwise remove this and load it here itself
loadNavMenu();
}
protected abstract void loadNavMenu();
// call this method whenever you enter new activity and load the fragment here.
public void showFragment(Fragment object, String title) {
FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
transaction.replace(R.id.fragment, object);
transaction.commit();
}}
Those activities which need the drawer menu can inherit above class. Not inflate all the layout's inside FrameLayout only.
public class MainActivity extends BaseDrawerLayoutActivity {
public static final String TAG = OLMSActivity.class.getSimpleName();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//the method below will call the BaseDrawerLayoutActivity method and change the fragment for you to see.
showFragment(new MyProfileFragment(), "My Profile");
}
#Override
protected void loadNavMenu() {
NavItems.clear();
//load your menu items
}
private void loadNavFavourites(){
//todo
}}
MyProfileFragment is just a class with fragment and this one call inflate a layout in its OnCreateView method.
I am trying to create an array of ImageView controls and add drawable resources to it. I am getting
Caused by: java.lang.NullPointerException: Attempt to invoke virtual
method 'void android.widget.ImageView.setBackgroundResource(int)' on a
null object reference
Here is the code:
public class MultipleChoice extends ActionBarActivity {
TextView Left;
TextView Operator;
TextView Right;
TextView GameTimer;
TextView CorrectAnswers;
ImageView imageView[] = new ImageView[11];
int imageViewNumber;
Button btnStart;
int intLeft;
int intOperator;
int intRight;
int intCorrectAnswer;
int intCorrectAnswers;
String strCorrectAnswer;
CountDownTimer problemtimer = new CountDownTimer(10000,1000) {
#Override
public void onTick(long millisUntilFinished) {
}
#Override
public void onFinish() {
NextProblem();
}
};
CountDownTimer gametimer = new CountDownTimer(60000,1000) {
#Override
public void onTick(long millisUntilFinished) {
GameTimer.setText("Time Left: " + millisUntilFinished / 1000);
}
#Override
public void onFinish() {
problemtimer.cancel();
gametimer.cancel();
GameTimer.setText("Time Left: 0");
btnStart.setEnabled(true);
}
};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_multiple_choice);
SetStartupValues();
}
private void SetStartupValues(){
Left = (TextView) findViewById(R.id.Left);
Operator = (TextView) findViewById(R.id.Operator);
Right = (TextView) findViewById(R.id.Right);
GameTimer = (TextView) findViewById(R.id.Timeleft);
CorrectAnswers = (TextView) findViewById(R.id.CorrectAnswers);
btnStart = (Button) findViewById(R.id.btnStart);
Left.setText("");
Operator.setText("");
Right.setText("");
GameTimer.setText("Time Left: 60");
CorrectAnswers.setText("Correct: 0");
intCorrectAnswers = 0;
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
public void btnStart_Click(View view) {
// Do something in response to button click
SetStartupValues();
NextProblem();
gametimer.start();
btnStart.setEnabled(false);
}
public void NextProblem(){
intLeft = new Random().nextInt(100);
intRight= new Random().nextInt(100);
intOperator= new Random().nextInt(3);
Left.setText(String.valueOf(intLeft));
Right.setText(String.valueOf(intRight));
imageViewNumber=0;
switch(intOperator){
case 0:
Operator.setText("+");
intCorrectAnswer = intLeft + intRight;
break;
case 1:
Operator.setText("-");
intCorrectAnswer=intLeft-intRight;
break;
case 2:
Operator.setText("X");
intCorrectAnswer=intLeft*intRight;
break;
}
strCorrectAnswer = String.valueOf(intCorrectAnswer);
GetNumbers(strCorrectAnswer);
problemtimer.start();
}
private void GetNumbers(String strNumber){
LinearLayout ll = (LinearLayout)findViewById(R.id.linearLayout1);
int L = strNumber.length();
String c;
for (int i = 0;i<L-1;i++){
c=strNumber.substring(i,i+1);
switch (c){
case "1":
imageView[imageViewNumber].setBackgroundResource(R.drawable.one);
ll.addView(imageView[imageViewNumber]);
break;
case "2":
imageView[imageViewNumber].setBackgroundResource(R.drawable.two);
ll.addView(imageView[imageViewNumber]);
break;
case "3":
imageView[imageViewNumber].setBackgroundResource(R.drawable.three);
ll.addView(imageView[imageViewNumber]);
break;
case "4":
imageView[imageViewNumber].setBackgroundResource(R.drawable.four);
ll.addView(imageView[imageViewNumber]);
break;
case "5":
imageView[imageViewNumber].setBackgroundResource(R.drawable.five);
ll.addView(imageView[imageViewNumber]);
break;
case "6":
imageView[imageViewNumber].setBackgroundResource(R.drawable.six);
ll.addView(imageView[imageViewNumber]);
break;
case "7":
imageView[imageViewNumber].setBackgroundResource(R.drawable.seven);
ll.addView(imageView[imageViewNumber]);
break;
case "8":
imageView[imageViewNumber].setBackgroundResource(R.drawable.eight);
ll.addView(imageView[imageViewNumber]);
break;
case "9":
imageView[imageViewNumber].setBackgroundResource(R.drawable.nine);
ll.addView(imageView[imageViewNumber]);
break;
case "0":
imageView[imageViewNumber].setBackgroundResource(R.drawable.zero);
ll.addView(imageView[imageViewNumber]);
break;
}
}
}
The error occurs in the Switch statement on the lines like
imageView[imageViewNumber].setBackgroundResource(R.drawable.zero);
What am I doing wrong?
Here is my Layout file
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent"
android:layout_height="match_parent" android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
android:paddingBottom="#dimen/activity_vertical_margin" tools:context=".MultipleChoice"
android:minWidth="30dp"
android:focusableInTouchMode="false">
<TextView android:text="#string/LeftText" android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/Left"
android:layout_below="#+id/Timeleft"
android:layout_toLeftOf="#+id/Operator"
android:layout_toStartOf="#+id/Operator" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/OperatorText"
android:id="#+id/Operator"
android:layout_below="#+id/Timeleft"
android:layout_centerHorizontal="true" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/RightText"
android:id="#+id/Right"
android:layout_below="#+id/Timeleft"
android:layout_toRightOf="#+id/Operator"
android:layout_toEndOf="#+id/Operator" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/StartButton"
android:id="#+id/btnStart"
android:layout_alignParentBottom="true"
android:layout_centerHorizontal="true"
android:onClick="btnStart_Click"
android:enabled="true"
android:focusable="false" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/TimeLeft"
android:id="#+id/Timeleft"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Correct: 0"
android:id="#+id/CorrectAnswers"
android:layout_alignTop="#+id/Timeleft"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true" />
<LinearLayout
android:orientation="horizontal"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:id="#+id/LinearContainer"
android:layout_centerVertical="true"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:baselineAligned="false">
<LinearLayout
android:orientation="horizontal"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/linearLayout1"
android:layout_weight="1"
android:gravity="center_horizontal">
</LinearLayout>
<LinearLayout
android:orientation="horizontal"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="1"
android:id="#+id/linearLayout2"
android:gravity="center_horizontal">
</LinearLayout>
<LinearLayout
android:orientation="horizontal"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="1"
android:id="#+id/linearLayout3"
android:gravity="center_horizontal">
</LinearLayout>
</LinearLayout>
</RelativeLayout>
You dont have objects in your "imageView" array.
Initialize it with values:
for(int i = 0; i < imageView.lenght; i++) imageView[i] = new ImageView(context);
So you can use then properly.
I've got a popupWindow that is triggered from the Activity Bar in Main Event. The buttons in the popup window are not triggering their respective listeners in showPopup(). Much of this popupWindow structure works fine when initiated from a fragment. I cannot identify the root cause of this. Any suggestions? Thanks.
public class MainActivity extends Activity{
private final static String TAB_KEY_INDEX = "TAB_KEY";
public static Context appContext;
private PopupWindow popupWindow;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
appContext = getApplicationContext();
//put Actionbar in tab mode
ActionBar actionBar = getActionBar();
actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);
//set titles for tabs
ActionBar.Tab tab1 = actionBar.newTab().setText("Tab1");
//create instances of each of the fragments
Fragment tab1Fragment = new Tab1Fragment();
//attach those fragment instances to their respective tabs
tab1.setTabListener(new MyTabsListener(tab1Fragment));
//add each tab to the ActionBar
actionBar.addTab(tab1);
if (savedInstanceState == null){//...do nothing
}else if (savedInstanceState != null){
actionBar.setSelectedNavigationItem(savedInstanceState.getInt(TAB_KEY_INDEX,0));
}
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch(item.getItemId()) {
case R.id.menuitem_popup:
showPopup();
return true;
}return false;
}
#Override
public boolean onCreateOptionsMenu(Menu menu){
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.main, menu);
return true;
}
#Override
protected void onSaveInstanceState(Bundle outState){
super.onSaveInstanceState(outState);
outState.putInt(TAB_KEY_INDEX, getActionBar().getSelectedNavigationIndex());
}
private void showPopup() {
Button btnDismiss, btnSaveRecord;
try {
LayoutInflater layoutInflater = (LayoutInflater) MainActivity.this.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View layout = layoutInflater.inflate(R.layout.popup_layout, null);
popupWindow = new PopupWindow(layout, 580, 500, true);
popupWindow.showAtLocation(layout, Gravity.CENTER, 0, 40);
btnDismiss=(Button)MainActivity.this.findViewById(R.id.btnDismissxml);
btnDismiss.setOnClickListener(new OnClickListener() {
//#Override
public void onClick(View arg0) {
popupWindow.dismiss();
}
});
btnSaveRecord=(Button)MainActivity.this.findViewById(R.id.btnSaveRecordxml);
btnSaveRecord.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
saveRecord();
}
});
} catch (Exception e) {
e.printStackTrace();
}
}
public void saveRecord(){
Toast.makeText(MainActivity.this.getApplicationContext(), "Event saveRecord() triggered.", Toast.LENGTH_SHORT).show();
}
}
Here's popup_layout.xml per request. Thanks.
<?xml version="1.0" encoding="utf-8"?>
<TableLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:gravity="center_horizontal"
android:background="#drawable/customborder">
<TableRow>
<TextView
android:id="#+id/tv"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="This is Fragment3" />
</TableRow>
<TableRow>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Species:" />
<EditText
android:id="#+id/textboxSpeciesxml"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_span="3"
android:text="(table is empty)"/>
</TableRow>
<TableRow>
<Button
android:id="#+id/btnSaveRecordxml"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="SAVE" />
<Button
android:id="#+id/btnUpdateRecordxml"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="UPDATE" />
<Button
android:id="#+id/btnDeleteRecordxml"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="DELETE" />
<Button
android:id="#+id/btnClearFormxml"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="CLEAR" />
</TableRow>
<TableRow>
<Button
android:id="#+id/btnFirstRecordxml"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="#string/pszFirstRecordButton"/>
<Button
android:id="#+id/btnPreviousRecordxml"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="#string/pszPreviousRecordButton"/>
<Button
android:id="#+id/btnNextRecordxml"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="#string/pszNextRecordButton"/>
<Button
android:id="#+id/btnLastRecordxml"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="#string/pszLastRecordButton"/>
</TableRow>
<TableRow>
<Button
android:id="#+id/btnPurgeTablexml"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_span="2"
android:text="Purge Table!" />
<Button
android:id="#+id/btnDismissxml"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_column="3"
android:text="Dismiss" />
</TableRow>
</TableLayout>
If btnDismissxml and btnSaveRecordxml are your buttons in popup window, you could find them using layout.findViewById rather than MainActivity.this.findViewById. Use the following code:
View layout = (TableLayout) layoutInflater.inflate(R.layout.popup_layout, null);
// ...
btnDismiss=(Button) layout.findViewById(R.id.btnDismissxml);
btnDismiss.setOnClickListener(new OnClickListener() {
// ...
});
btnSaveRecord=(Button) layout.findViewById(R.id.btnSaveRecordxml);
btnSaveRecord.setOnClickListener(new OnClickListener() {
// ...
});
I have used fragments
activity_fragment_demo.xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".FragmentDemo" >
<LinearLayout
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical" >
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content" >
<Button
android:id="#+id/button1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="1"
android:text="Button" />
<Button
android:id="#+id/button2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="1"
android:text="Button" />
</LinearLayout>
<LinearLayout
android:id="#+id/simple_fragment"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
</LinearLayout>
</LinearLayout>
</LinearLayout>
FragmentDemo.java
public class FragmentDemo extends FragmentActivity implements OnClickListener {
Button b1, b2;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_fragment_demo);
b1 = (Button) findViewById(R.id.button1);
b2 = (Button) findViewById(R.id.button2);
b1.setOnClickListener(this);
b2.setOnClickListener(this);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.fragment_demo, menu);
return true;
}
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
switch (v.getId()) {
case R.id.button1:
addFragment(new F1(this), false,
FragmentTransaction.TRANSIT_FRAGMENT_OPEN);
break;
case R.id.button2:
addFragment(new F2(this), false,
FragmentTransaction.TRANSIT_FRAGMENT_OPEN);
break;
default:
break;
}
}
void addFragment(Fragment fragment, boolean addToBackStack, int transition) {
FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
ft.replace(R.id.simple_fragment, fragment);
ft.setTransition(transition);
if (addToBackStack)
ft.addToBackStack(null);
ft.commit();
}
}
F1.java
public class F1 extends Fragment {
Context c;
View v;
public F1(FragmentDemo fragmentDemo) {
// TODO Auto-generated constructor stub
this.c = fragmentDemo;
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// TODO Auto-generated method stub
v = inflater.inflate(R.layout.f1, container, false);
return v;
}
}
F2.java
public class F2 extends Fragment {
Context c;
View v;
public F2(FragmentDemo fragmentDemo) {
// TODO Auto-generated constructor stub
this.c = fragmentDemo;
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// TODO Auto-generated method stub
v = inflater.inflate(R.layout.f2, container, false);
return v;
}
}
OUTPUT SCREEN: -- > WHEN I CLICK BUtton on lefthand side
Similarly for next button
Now HOW CAN I Merge the thow buttons like below
Using fragments i have used .....
If i click on button once Activity-A1 must display in button
below .....
similarly If i click on button again Activity-A2 must display
below
Then if i click on third time ...... Activity-A1 must display
again
A Boolean nature of single button that repeats its cycle !
How to achieve this !
There are many ways to do this but here is a simple solution.
First change activity_fragment_demo.xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".FragmentDemo" >
<LinearLayout
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical" >
<FrameLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center_horizontal">
<Button
android:id="#+id/button1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Button" />
<Button
android:id="#+id/button2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Button"
android:visibility="gone"/>
</FrameLayout>
<LinearLayout
android:id="#+id/simple_fragment"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
</LinearLayout>
</LinearLayout>
</LinearLayout>
next in FragmentDemo.java just change your onClick method like this:
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
switch (v.getId()) {
case R.id.button1:
addFragment(new F1(this), false,
FragmentTransaction.TRANSIT_FRAGMENT_OPEN);
b1.setVisibility(View.GONE);
b2.setVisibility(View.VISIBLE);
break;
case R.id.button2:
addFragment(new F2(this), false,
FragmentTransaction.TRANSIT_FRAGMENT_OPEN);
b2.setVisibility(View.GONE);
b1.setVisibility(View.VISIBLE);
break;
default:
break;
}
}
Your Activity could keep track of the state with a boolean. For example like this:
private boolean state = false;
#Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.button1:
state = !state;
if (state) {
addFragment(new F2(this), false,
FragmentTransaction.TRANSIT_FRAGMENT_OPEN);
} else {
addFragment(new F1(this), false,
FragmentTransaction.TRANSIT_FRAGMENT_OPEN);
}
break;
default:
break;
}
}