I recently migrated to androidX for developing my app.But when I run the app on my device ,it always shows "App isn't responding" error message. I have just added the drawer activity and two fragments to it. When I run the app, it lags continuously.Even the sliding of drawer takes much time and also when I click the button on the fragment ,it's click event is responding after long time.Don't know what exactly is going wrong.My other projects, which use support library, aren't lagging although they contain much more than just 2 fragments.Thanks for any help.
My drawer activity code
public class DrawerActivity extends MAWBaseActivity implements NavigationView.OnNavigationItemSelectedListener {
DrawerLayout drawer;
NavigationView navigationView;
ActionBarDrawerToggle toggle;
FrameLayout logNWorkContainer;
ImageView ivUserImage;
TextView tvUserName;
TextView tvUserDesignation;
TextView tvUserCode;
View navHeader;
LinearLayout activityProgressLayout;
ProgressBar activityProgress;
/**
* Intent
*
* #param context calling activity context
*/
public static void show(Context context) {
Intent intent = new Intent(context, DrawerActivity.class);
context.startActivity(intent);
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_drawer);
overridePendingTransition(R.anim.slide_in, R.anim.slide_out);
Toolbar toolbar = findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
logNWorkContainer = findViewById(R.id.logNWorkContainer);
drawer = findViewById(R.id.drawer_layout);
navigationView = findViewById(R.id.nav_view);
activityProgressLayout = findViewById(R.id.activityProgressLayout);
activityProgress = findViewById(R.id.activityProgress);
toggle = new ActionBarDrawerToggle(
this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
drawer.addDrawerListener(toggle);
toggle.syncState();
navigationView.setNavigationItemSelectedListener(this);
// Navigation view header
navHeader = navigationView.getHeaderView(0);
ivUserImage = navHeader.findViewById(R.id.ivUserImage);
tvUserName = navHeader.findViewById(R.id.tvName);
tvUserDesignation = navHeader.findViewById(R.id.tvUserDesignation);
tvUserCode = navHeader.findViewById(R.id.tvUserCode);
UserData userData = UserCache.user().getUserData();
if (userData == null) {
Login.show(this);
finish();
}
if (userData != null) {
// getNotificationAPICall(userData);
String name = ifNullReplace(userData.getFirstName(), EMPTY) + " " + ifNullReplace(userData
.getLastName(), EMPTY);
tvUserName.setText(name);
if (userData.getCode() == null) {
tvUserCode.setVisibility(View.GONE);
} else {
tvUserCode.setText("Emp No :- " + userData.getCode());
}
if (userData.getUserDesignation() == null || userData.getUserDesignation().equalsIgnoreCase(EMPTY)) {
tvUserDesignation.setVisibility(View.GONE);
} else {
tvUserDesignation.setVisibility(View.VISIBLE);
tvUserDesignation.setText(ifNullReplace(userData.getUserDesignation(), EMPTY));
}
ivUserImage.setImageResource(R.drawable.ic_user_new);
String url = UrlConstant.GET_THUMB_BY_NAME + userData.getPhoto() + UrlConstant.SIZE_100 + UrlConstant.IMAGE_USER;
UIUtils.loadRoundImage(url, ivUserImage, R.drawable.ic_profile_small);
}
HomeFragment homeFragment = new HomeFragment();
beginFragmentTransaction(homeFragment, "Home");
}
/**
* Begin fragment transaction
*
* #param fragment fragment
* #param name name of menu
*/
public void beginFragmentTransaction(Fragment fragment, String name) {
if (drawer.isDrawerOpen(GravityCompat.START)) {
drawer.closeDrawer(GravityCompat.START);
}
getSupportActionBar().setTitle(name);
// Insert the fragment by replacing any existing fragment
FragmentManager fragmentManager = getSupportFragmentManager();
fragmentManager.beginTransaction().replace(R.id.logNWorkContainer, fragment).commit();
}
/**
* Get activity progress
*
* #return progressbar
*/
public ProgressBar getActivityProgress() {
return activityProgress;
}
#Override
public void onBackPressed() {
drawer = findViewById(R.id.drawer_layout);
if (drawer.isDrawerOpen(GravityCompat.START)) {
drawer.closeDrawer(GravityCompat.START);
} else {
Dialogs.getInstance().showExitDialog(DrawerActivity.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.home_menu, 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_notifications) {
return true;
}
return super.onOptionsItemSelected(item);
}
#SuppressWarnings("StatementWithEmptyBody")
#Override
public boolean onNavigationItemSelected(MenuItem item) {
// Handle navigation view item clicks here.
int id = item.getItemId();
if (id == R.id.menu_home) {
HomeFragment homeFragment = new HomeFragment();
beginFragmentTransaction(homeFragment, getString(R.string.menu_home_label));
return true;
} else if (id == R.id.menu_calender) {
CalenderFragment calenderFragment = new CalenderFragment();
beginFragmentTransaction(calenderFragment, getString(R.string.menu_company_calender_label));
return true;
}
DrawerLayout drawer = findViewById(R.id.drawer_layout);
drawer.closeDrawer(GravityCompat.START);
return true;
}
}
** There are no errors in logs.
Also I have added mapview in first fragment and the second fragment contains calenderview.If needed I'll post the whole code here, but it just contains location service and some api calls that are triggered on button click.
The logs show this E/MultiWindowProxy: getServiceInstance failed! I'm searching for it.
To fix the E/MultiWindowProxy: getServiceInstance failed! error, I think you need <uses-library android:required="false" android:name="com.sec.android.app.multiwindow"> </uses-library> in your Manifest file.
As for the app is not responding error, I think your problem might be that you are requesting user information without the necessary permissions. Otherwise, I'd try to run the app in debug and see which line (or section of code) your code is getting stuck executing.
Related
I am using navigation menu in an Activity. When I click menu, it goes to particular fragment that time I give addtobackstack(null). I want to fix these 2 issues:
I want to show do you want to exit app through a popup In the back fragment
Assume that I traverse from Fragment A to B and then B to C. If I give back in the Fragment C I want to come the main page, without showing the Fragment B.
This is my Home Activity:
package school.wyse.app.activities;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
public class ParentHomeActivity extends AppCompatActivity
implements NavigationView.OnNavigationItemSelectedListener {
ServerUtils servutil;
GridLayoutManager grid;
Toolbar toolbar;
private View navHeader;
LinearLayout profile;
ImageView msglist;
ArrayList<StudentProfile> lang_list_new;
public RecyclerView studentsListRecyclerView;
public ParentMenuDashoard mStudAdapter;
StudentProfile[] profiles;
private StudentProfile[] studentCachedData;
Context ctx;
DrawerLayout drawer;
ImageView imageViewstaff;
String tenent_id,profilename,image,userphone;
Integer id,roleid;
String backStateName;
TextView profile_phone,profile_name;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
try {
setContentView(R.layout.activity_parent_home);
backStateName = this.getClass().getName();
ctx=this;
Toast.makeText(ctx, "backStateName--"+backStateName, Toast.LENGTH_SHORT).show();
toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(
this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
drawer.setDrawerListener(toggle);
toggle.syncState();
NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
navigationView.setNavigationItemSelectedListener(this);
navHeader=navigationView.getHeaderView(0);
studentsListRecyclerView = (RecyclerView) navHeader.findViewById(R.id.messageWindowRecycler);
ParentDashboard parentDashboard = new ParentDashboard();
FragmentManager manager = getSupportFragmentManager();
manager.beginTransaction().replace(R.id.content_frame, parentDashboard, parentDashboard.getTag()).commit();
toolbar.setTitle("Dashboard");
} catch (Exception e) {
e.printStackTrace();
}
}
#Override
public void onBackPressed() {
try {
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
if (drawer.isDrawerOpen(GravityCompat.START)) {
drawer.closeDrawer(GravityCompat.START);
} else {
super.onBackPressed();
}
} catch (Exception e) {
e.printStackTrace();
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.home, 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_msg) {
return true;
}*/
return super.onOptionsItemSelected(item);
}
#SuppressWarnings("StatementWithEmptyBody")
#Override
public boolean onNavigationItemSelected(MenuItem item) {
// Handle navigation view item clicks here.
int id = item.getItemId();
if (id == R.id.nav_dashboard) {
ParentDashboard parentDashboard = new ParentDashboard();
FragmentManager manager = getSupportFragmentManager();
manager.beginTransaction().replace(R.id.content_frame, parentDashboard, parentDashboard.getTag()).addToBackStack(null).commit();
//toolbar.setTitle("Dashboard");
} else if (id == R.id.nav_teachers) {
TeacherList teacherList = new TeacherList();
FragmentManager manager = getSupportFragmentManager();
// manager.beginTransaction().replace(R.id.id_content_frame, accountsMenuListFragment, "AccountsMenu").addToBackStack(" ").commit();
manager.beginTransaction().replace(R.id.content_frame, teacherList, teacherList.getTag()).addToBackStack(null).commit();
// toolbar.setTitle("Teachers");
} else if (id == R.id.nav_attendance) {
AttendanceFragment attendanceFragment = new AttendanceFragment();
FragmentManager manager = getSupportFragmentManager();
manager.beginTransaction().replace(R.id.content_frame, attendanceFragment, attendanceFragment.getTag()).addToBackStack(null).commit();
// toolbar.setTitle("Attendance");
} else if (id == R.id.nav_consumablity) {
ParentConsumablityFragment parentConsumablityFragment = new ParentConsumablityFragment();
FragmentManager manager = getSupportFragmentManager();
manager.beginTransaction().replace(R.id.content_frame, parentConsumablityFragment, parentConsumablityFragment.getTag()).addToBackStack(null).commit();
// toolbar.setTitle("Attendance");
}
else {
}
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
drawer.closeDrawer(GravityCompat.START);
return true;
}
}
Okay, sorry for late reply
This part goes in onBackPressed() of your activity, which basically check if you have fragments attached (so it won't perform the native back, which closes the app)
if (childFragments.size() > 0) {
if (childFragments.get((childFragments.size() - 1)) != null) {
childFragments.remove(childFragments.size() - 1);
return;
}
}
All you have to do is add/remove items to this array every time you attach / detach fragments :)
For your particular case when you are on fragment C and want to go back to fragment A without showing fragment B, I suggest you make a public function that remove all fragments from ArrayList except last one (from position 0)
Use below code in mainactivity where you want to show appexit:
#Override
public void onBackPressed() {
if (doubleBackToExitPressedOnce) {
super.onBackPressed();
finish();
return;
}
this.doubleBackToExitPressedOnce = true;
Toast.makeText(this, "Please click BACK again to exit", Toast.LENGTH_SHORT).show();
new Handler().postDelayed(new Runnable() {
#Override
public void run() {
doubleBackToExitPressedOnce = false;
}
}, 2000);
}
When moving fragment A to B do not add "addbackstack". When moving fragment B to C add "addbackstack("C")"
first of all, you have to take care of your second issue as it will lead to easy handle for the first issue, hence you have to take care of how to initiate the fragments in order to always coming to the first fragment while hitting back regardless the flow of fragments that lead to the current fragment, to do so, just initiate the fragments like the following:
/**
* To initiate any fragment
*/
private void showAnyFragment(Fragment fragmentToShow) {
getSupportFragmentManager().popBackStack();
FrameLayout frameLayout = (FrameLayout) findViewById(R.id.content);
frameLayout.setVisibility(View.VISIBLE);
getSupportFragmentManager().beginTransaction()
.replace(R.id.content, fragmentToShow)
.addToBackStack(null)
.commit();
}
/**
* When (for a reason) you want to initiate the main fragment (FragmentA)
*/
private void homeClicked() {
getSupportFragmentManager().popBackStack();
}
Now, fragmentA is your main fragment, when going from A to B to C to D and click back button it will go back to A directly.
Coming to your second issue, it will be straight forward as you already keeping only fragmentA always in the back stack, so onBackPressed() function of the Activity will not be called unless there are No other fragment other than FragmentAis being displayed(e.g if you are in fragmentC and you click back button, the onBackPressed() function will not be called), so you are sure that when you come inside onBackPressed() function of the activity that the currently running fragment is FragmentA which is your main page fragment.
so if you want to display a popup while the user trying to exit the app (he would be in FragmentA and hiitting Back), all you have to do is to override the onBackPressed() method of the MainActivity that holds the fragments:
#Override
public void onBackPressed() {
// the user here is in FragmentA(main page),
and he is clicking back to exit the app.
// TODO show popup here or do whatever you want
}
I have a navigation drawer activity with fragments within it by using a fragment container. I have three fragments within it and I need one of it named locate_login to not contain my navigation drawer.
MainActivity.java
public class MainActivity extends AppCompatActivity
implements NavigationView.OnNavigationItemSelectedListener {
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout); //nav drawer
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//Set the fragment initially
locate_login fragment = new locate_login();
android.support.v4.app.FragmentTransaction fragmentTransaction = getSupportFragmentManager().beginTransaction();
fragmentTransaction.replace(R.id.fragment_container, fragment);
fragmentTransaction.commit();
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(
this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
drawer.setDrawerListener(toggle);
toggle.syncState();
NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
navigationView.setNavigationItemSelectedListener(this);
}
public void onSelectFragment(View v){ //ignore this
Fragment newFragment;
if(v == findViewById(R.id.trigger)){
newFragment = new locate_after();
}
else{
newFragment = new locate_before();
}
FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
transaction.replace(R.id.fragment_container, newFragment);
transaction.addToBackStack(null);
transaction.commit();
}
#Override
public void onBackPressed() {
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
if (drawer.isDrawerOpen(GravityCompat.START)) {
drawer.closeDrawer(GravityCompat.START);
} else {
super.onBackPressed();
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.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);
}
#SuppressWarnings("StatementWithEmptyBody")
#Override
public boolean onNavigationItemSelected(MenuItem item) {
// Handle navigation view item clicks here.
int id = item.getItemId();
if (id == R.id.nav_camera) {
// Handle the camera action
} else if (id == R.id.nav_gallery) {
} else if (id == R.id.nav_slideshow) {
} else if (id == R.id.nav_manage) {
} else if (id == R.id.nav_share) {
} else if (id == R.id.nav_send) {
}
drawer.closeDrawer(GravityCompat.START);
return true;
}
}
Here is my locate_login fragment
public class locate_login extends Fragment{
public locate_login () {
// Required empty public constructor
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.locate_login, container, false);
// Inflate the layout for this fragment
return rootView;
}
}
I will highly appreciate it if the answer will be detailed since I'm a beginner on Android Studio.
Create a class for some constant parameter. Declare some constant variable like:
Let say StringConstant.java :
public static final int LOCK_DRAWER = 1;
public static final int SHOW_DRAWER = 2;
When navigating from the drawer, use an Intent object as:
If you want to show the drawer, use:
intent.putExtra("SHOW_DRAWER", StringConstant.SHOW_DRAWER);
OR
If you do not want to show the drawer, use:
intent.putExtra("SHOW_DRAWER", StringConstant.LOCK_DRAWER);
Retrieve intent from your fragment class, you say locate_login.
int status = getActivity.getIntent().getIntExtra("SHOW_DRAWER", 0);
Check status:
if (status == String.Constant.LOCK_DRAWER){
lockDrawer();
}
public void lockDrawer() {
drawerLayout.setDrawerLockMode(DrawerLayout.LOCK_MODE_LOCKED_CLOSED);
}
To unlock the drawer:
public void unlockDrawer() {
drawerLayout.setDrawerLockMode(DrawerLayout.LOCK_MODE_UNLOCKED);
}
I got a problem that DrawerLayout does not close smoothly and it stops in the middle for a while, it totally closes after finish replacing fragment. In coding I close DrawerLayout before replacing fragment (productList class). In productList class, it calls asynctask to get all the product list from server meanwhile running progress bar. Ideally when user clicks menu, DrawerLayout will close at once and productList fragment will be loading all the product list. It seems to me DrawerLayout close event waits for productList's asynctask. Any suggestion greatly appreciated.
public class MainActivity extends AppCompatActivity
implements NavigationView.OnNavigationItemSelectedListener, View.OnClickListener {
public String tag = "MainActivity";
Context mContext;
//User Object
User user;
//Control
TextView txtName, txtPosition, txtLogout;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mContext = this;
user = Constants.getUser();
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(
this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
drawer.addDrawerListener(toggle);
toggle.syncState();
NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
//NavigationView Header
View headerView = navigationView.getHeaderView(0);
txtName = (TextView) headerView.findViewById(R.id.nav_header_main_name) ;
txtName.setText(user.getName().toString());
txtLogout = (TextView) headerView.findViewById(R.id.nav_header_main_logout);
txtLogout.setOnClickListener(this);
navigationView.setNavigationItemSelectedListener(this);
//Add Menu in navigationView
Menu myMenu = navigationView.getMenu();
myMenu.clear();
myMenu.add(0,Integer.parseInt("01"),0,"Product List");
}
#Override
public void onBackPressed() {
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
if (drawer.isDrawerOpen(GravityCompat.START)) {
drawer.closeDrawer(GravityCompat.START);
} else {
super.onBackPressed();
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
#SuppressWarnings("StatementWithEmptyBody")
#Override
public boolean onNavigationItemSelected(MenuItem item) {
//close drawer
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
drawer.closeDrawer(GravityCompat.START);
// replace fragment
int id = item.getItemId();
FragmentManager fragmentManager = getSupportFragmentManager();
if(Constants.DEBUG) {
Toast.makeText(mContext, " Menu Id " + String.valueOf(id), Toast.LENGTH_LONG).show();
}
fragmentManager.beginTransaction()
.replace(R.id.container,new productList())
.commit();
return true;
}
#Override
public void onClick(View v) {
//Log out onclick
if(v.getId() == R.id.nav_header_main_logout){
this.finish();
}
}
}
This probably happens beacuse the Navigation Drawer's animation and the creation of the Fragment happens at the same time.
You can solve it by starting your Fragment with a small delay-
handler.postDelayed(new Runnable() {
#Override
public void run() {
// replace fragment
int id = item.getItemId();
FragmentManager fragmentManager = getSupportFragmentManager();
if(Constants.DEBUG) {
Toast.makeText(mContext, " Menu Id " + String.valueOf(id), Toast.LENGTH_LONG).show();
}
fragmentManager.beginTransaction()
.replace(R.id.container,new productList())
.commit();
}
}, 300);
I am trying to extend other activities into Navigation Bar Activity, I want to use content of the Activity with Navigation Drawer, but when I use setcontentView, Navigation Bar does not work.
This is my Navigation Bar Activity :
:
public class navigationdrawer extends AppCompatActivity
implements NavigationView.OnNavigationItemSelectedListener {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_navigationdrawer);
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(
this, drawer, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
drawer.setDrawerListener(toggle);
toggle.syncState();
NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
navigationView.setNavigationItemSelectedListener(this);
}
#Override
public void onBackPressed() {
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
if (drawer.isDrawerOpen(GravityCompat.START)) {
drawer.closeDrawer(GravityCompat.START);
} else {
super.onBackPressed();
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.navigationdrawer, 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);
}
#SuppressWarnings("StatementWithEmptyBody")
#Override
public boolean onNavigationItemSelected(MenuItem item) {
// Handle navigation view item clicks here.
int id = item.getItemId();
if (id == R.id.nav_dashboard) {
Intent i = new Intent(navigationdrawer.this, dashboard.class);
startActivity(i);
// Handle the camera action
} else if (id == R.id.nav_community) {
} else if (id == R.id.nav_recipes) {
Intent i = new Intent(navigationdrawer.this, Recipe.class);
startActivity(i);
} else if (id == R.id.nav_leaderboard) {
} else if (id == R.id.nav_upload) {
} else if (id == R.id.nav_mypics) {
} else if (id == R.id.nav_myvideos) {
} else if (id == R.id.nav_settings) {
} else if (id == R.id.nav_contactus) {
}
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
drawer.closeDrawer(GravityCompat.START);
return true;
}
}
This is my Second Activity :
public class Recipe extends navigationdrawer{
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// setContentView(new View(this));
// Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
// setSupportActionBar(toolbar);
}
}
I have commented setcontentview statement as I know that setcontentview is getting called in the Navigation Drawer Activity but I want Navigation Drawer and the content both. How to achieve this task?
Use fragment instead of activities
Fragment is an part of activity. so, if you want to use singledrawer throughout the app then it is better to use fragment inside your navigationbar activity
note :
use fragment view inside your navigation drawer activity
like
if (id == R.id.nav_dashboard) {
// write code for fragment replacement
}
Currently Used Google Navigation Drawer, having some problem when user backpress.
When user backpress, they didn't update menu Item
Example When I click the App. The sequence are A>B>C>B>C ,if I backpress I wanted to be C>B>A. How should I code this way out ?
My code
public class MainActivity extends AppCompatActivity {
private String appTitle;
private Toolbar toolbar;
private NavigationView navigationView;
private DrawerLayout drawerLayout;
private TextView toolbarTitle;
private Fragment fragment;
private FragmentManager fragmentManager;
private Title title;
private MenuItem menuItem2;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//Actionbar
toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
toolbarTitle = (TextView) toolbar.findViewById(R.id.toolbar_title);
toolbarTitle.setTextColor(Color.parseColor("#FFFFFF"));
setTitle("");
fragmentManager = getSupportFragmentManager();
fragment= new HomeFragment();
title = new Title(getApplicationContext());
fragmentManager.beginTransaction().replace(R.id.content_frame,fragment , title.getStrHome()).commit();
navigationView = (NavigationView) findViewById(R.id.navigation_view);
navigationView.setNavigationItemSelectedListener(new NavigationView.OnNavigationItemSelectedListener() {
#Override
public boolean onNavigationItemSelected(MenuItem menuItem) {
menuItem2 = menuItem;
menuItem.setChecked(true);
drawerLayout.closeDrawers();
if (menuItem.getItemId() == R.id.nav_home) {
fragment = new HomeFragment();
appTitle = title.getStrHome();
} else if ((menuItem.getItemId() == R.id.nav_direction)) {
fragment = new DirectionFragment();
appTitle = title.getStrDirection();
} else if ((menuItem.getItemId() == R.id.nav_more)) {
fragment = new MoreFragment();
appTitle = title.getStrMore();
} else if((menuItem.getItemId()==R.id.nav_directory)){
fragment = new DirectoryFragment();
appTitle = title.getStrDirectory();
}
else {
Toast.makeText(getApplicationContext(), "Error", Toast.LENGTH_SHORT).show();
}
replaceFragment(fragment,appTitle);
return true;
}
});
drawerLayout = (DrawerLayout) findViewById(R.id.drawer);
ActionBarDrawerToggle actionBarDrawerToggle =
new ActionBarDrawerToggle
(this,drawerLayout,toolbar,R.string.drawer_open,R.string.drawer_close){
#Override
public void onDrawerClosed(View drawerView) {
super.onDrawerClosed(drawerView);
}
#Override
public void onDrawerOpened(View drawerView) {
super.onDrawerOpened(drawerView);
}
};
drawerLayout.setDrawerListener(actionBarDrawerToggle);
actionBarDrawerToggle.syncState();
}
public void onBackPressed() {
if(drawerLayout.isDrawerOpen(GravityCompat.START)){
drawerLayout.closeDrawer(GravityCompat.START);
}
else {
if (fragmentManager.getBackStackEntryCount() > 0 ){
fragmentManager.popBackStack();
toolbarTitle.setText(appTitle);
menuItem2.setChecked(true);
} else {
finish();
}
}
}
public void replaceFragment(Fragment fragment, String tag){
toolbarTitle.setText(tag);
FragmentTransaction ft = fragmentManager.beginTransaction().replace(R.id.content_frame, fragment, tag);
ft.addToBackStack(tag);
ft.commit();
}
#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) {
int id = item.getItemId();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
}
As stated on the official page on Android tasks and back stack you can see how you can accomplish your desired behaviour using the FLAG_ACTIVITY_CLEAR_TOP in your Intent flags. This picture demonstrates it very well.
Your regular back button proceeds as:
When you specify this flag, you get a behavior like you need
Edit:
The official documentation states:
FLAG_ACTIVITY_CLEAR_TOP
If the activity being started is already running in the current task, then instead of launching a new instance of that activity, all of the
other activities on top of it are destroyed
This means, there will be no duplicates of your different Activities, and you will have a clean Back Stack.
In your example A>B>C>B>C would not be possible. Instead it would be A>B>C, since B and C already exist in the stack, they will not be added, but replaced instead.
Study the Android Activity Launch Mode.
here is the clear Explanation available.
Just take a look.