Android master / detail fragment with back button - android

I implemented a Drawer in the Main FragmentActivity, but don't know how to add a back navigation button in master/detail fragment.... Find several days still no answer.... any expert can help?
>> MainActivity with Drawer
public class MainActivity extends FragmentActivity {
private DrawerLayout mDrawerLayout;
private ListView mDrawerList;
private ActionBarDrawerToggle mDrawerToggle;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mTitle = mDrawerTitle = getTitle();
mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
CreateMenuItem();
getActionBar().setDisplayHomeAsUpEnabled(true);
getActionBar().setHomeButtonEnabled(true);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// toggle nav drawer on selecting action bar app icon/title
if (mDrawerToggle.onOptionsItemSelected(item)) {
return true;
}
// Handle action bar actions click
switch (item.getItemId()) {
case R.id.action_settings:
return true;
default:
return super.onOptionsItemSelected(item);
}
}
#Override
public boolean onPrepareOptionsMenu(Menu menu) {
boolean drawerOpen = mDrawerLayout.isDrawerOpen(mDrawerList);
menu.findItem(R.id.action_settings).setVisible(!drawerOpen);
return super.onPrepareOptionsMenu(menu);
}
private void displayView(int position) {
switch (position) {
case 0:
getSupportFragmentManager().beginTransaction().replace(R.id.fragment_frame, FragmentA.newInstance(), FragmentA.TAG).commit();
break;
case 1:
getSupportFragmentManager().beginTransaction().replace(R.id.fragment_frame, FragmentB.newInstance(), FragmentB.TAG).commit();
break;
case 2:
getSupportFragmentManager().beginTransaction().replace(R.id.fragment_frame, FragmentC.newInstance(), FragmentC.TAG).commit();
break;
case 3:
getSupportFragmentManager().beginTransaction().replace(R.id.fragment_frame, FragmentD.newInstance(), FragmentD.TAG).commit();
break;
default:
break;
}
mDrawerList.setItemChecked(position, true);
mDrawerList.setSelection(position);
mDrawerLayout.closeDrawer(mDrawerList);
}
}
>> Fragment A (Master Fragment)
public class FragmentA extends Fragment {
public FragmentA(){}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragmentA, container, false);
Button button= (Button) rootView.findViewById(R.id.button);
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
FragmentDetail fd = new FragmentDetail();
android.support.v4.app.FragmentTransaction ft = getFragmentManager().beginTransaction();
ft.replace(R.id.fragmentdetail, fd);
ft.setTransition(android.support.v4.app.FragmentTransaction.TRANSIT_FRAGMENT_OPEN);
ft.addToBackStack(null);
ft.commit();
}
});
return rootView;
}
>> FragmentDetail (Detail Fragment) > How to add a back button instead the navigator drawer menu
public class FragmentDetail extends Fragment {
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_detail, container, false);
return rootView;
}
}
I implemented a Drawer in the Main FragmentActivity, but don't know how to add a back navigation button in master/detail fragment.... Find several days still no answer.... any expert can help?

/**
* Handling back press of all fragments (Use this in fragmentactivity)
*
* */
#Override
public void onBackPressed() {
super.onBackPressed();
}

I usually set an onKeyListener to the View in onResume. From what I learned you have to take care to set setFocusableInTouchMode() and requestFocus on the View.
This is a sample of what I use for this purpose:
#Override
public void onResume() {
super.onResume();
getView().setFocusableInTouchMode(true);
getView().requestFocus();
getView().setOnKeyListener(new View.OnKeyListener() {
#Override
public boolean onKey(View v, int keyCode, KeyEvent event) {
if (event.getAction() == KeyEvent.ACTION_UP && keyCode == KeyEvent.KEYCODE_BACK){
// handle back button
getActivity().getSupportFragmentManager().popBackStack();
return true;
}
return false;
}
});
}

Related

I am using Web View inside a fragment. how to go back in web view

this is the web view fragment
public class Home extends Fragment {
public Home() {
// Required empty public constructor
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View v = inflater.inflate(R.layout.fragment_home, container, false);
WebView webView = (WebView)v.findViewById(R.id.webView1);
webView.getSettings().setJavaScriptEnabled(true);
webView.setWebViewClient(new WebViewClient());
webView.loadUrl("https://www.google.com");
return v;
}
}
I created web view inside other fragment not in main activity and when I press back button the app will close. so how to go back only inside web view (not through fragments)? please give me a solution.
here is my main activity
public class MainActivity extends AppCompatActivity implements BottomNavigationView.OnNavigationItemSelectedListener {
private static final String TAG = "MainActivity";
BottomNavigationView bottomNavigationView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
bottomNavigationView = findViewById(R.id.bottom_navigation_view);
bottomNavigationView.setOnNavigationItemSelectedListener(this);
bottomNavigationView.setSelectedItemId(R.id.navigation_home);
}
Home homeFragment = new Home();
Live_And_Event_Schedule live_and_event_scheduleFragment = new Live_And_Event_Schedule();
Photos photosFragment = new Photos();
Videos videosFragment = new Videos();
About aboutFragment = new About();
#Override
public boolean onNavigationItemSelected(#NonNull MenuItem item) {
switch (item.getItemId()){
case R.id.navigation_home:
getSupportFragmentManager().beginTransaction().setCustomAnimations(R.anim.fade_in, R.anim.fade_out).replace(R.id.center, homeFragment).commit();
return true;
case R.id.navigation_live_and_event_schedule:
getSupportFragmentManager().beginTransaction().setCustomAnimations(R.anim.fade_in, R.anim.fade_out).replace(R.id.center, live_and_event_scheduleFragment).commit();
return true;
case R.id.navigation_photos:
getSupportFragmentManager().beginTransaction().setCustomAnimations(R.anim.fade_in, R.anim.fade_out).replace(R.id.center, photosFragment).commit();
return true;
case R.id.navigation_videos:
getSupportFragmentManager().beginTransaction().setCustomAnimations(R.anim.fade_in, R.anim.fade_out).replace(R.id.center, videosFragment).commit();
return true;
case R.id.navigation_about:
getSupportFragmentManager().beginTransaction().setCustomAnimations(R.anim.fade_in, R.anim.fade_out).replace(R.id.center, aboutFragment).commit();
return true;
}
return false;
}
}
you can override onBackPressed in the Activity. save all fragmentTransaction before addToBackStack
#Override
public void onBackPressed() {
int count = getSupportFragmentManager().getBackStackEntryCount();
if (count == 0) {
super.onBackPressed();
//add extra code
} else {
getSupportFragmentManager().popBackStack();
}
}

Go back from a fragment to main fragment

This is my main activity where I am calling my fragments:
public class what extends AppCompatActivity {
private DrawerLayout mDrawerLayout;
private ActionBarDrawerToggle mToggle;
private ListView mDrawerList;
private ArrayAdapter<String> mAdapter;
private FragmentTransaction fragmentTransaction;
NavigationView navigationView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_what);
mDrawerLayout=(DrawerLayout)findViewById(R.id.drawer_layout);
mToggle=new ActionBarDrawerToggle(this, mDrawerLayout, R.string.open, R.string.close);
mDrawerLayout.addDrawerListener(mToggle);
mToggle.syncState();
fragmentTransaction= getSupportFragmentManager().beginTransaction();
fragmentTransaction.add(R.id.main_content,new mainfrag());
fragmentTransaction.commit();
ActionBar actionBar= getSupportActionBar();
actionBar.setDisplayHomeAsUpEnabled(true);
navigationView=(NavigationView)findViewById(R.id.nav_view);
navigationView.getMenu().getItem(1).setChecked(false);
navigationView.getMenu().getItem(0).setChecked(true);
navigationView.getMenu().getItem(2).setChecked(false);
navigationView.getMenu().getItem(3).setChecked(false);
navigationView.setNavigationItemSelectedListener(new NavigationView.OnNavigationItemSelectedListener() {
#Override
public boolean onNavigationItemSelected(#NonNull MenuItem item) {
switch (item.getItemId()) {
case R.id.nav_main:
navigationView.getMenu().getItem(1).setChecked(false);
navigationView.getMenu().getItem(2).setChecked(false);
navigationView.getMenu().getItem(3).setChecked(false);
navigationView.setCheckedItem(R.id.nav_main);
mDrawerLayout.closeDrawers();
fragmentTransaction=getSupportFragmentManager().beginTransaction();
fragmentTransaction.replace(R.id.main_content, new mainfrag());
fragmentTransaction.commit();
getSupportActionBar().setTitle(("SGPA and CGPA Calculator"));
item.setChecked(true);
break;
case R.id.nav_savedcal:
navigationView.getMenu().getItem(0).setChecked(false);
navigationView.getMenu().getItem(2).setChecked(false);
navigationView.getMenu().getItem(3).setChecked(false);
navigationView.setCheckedItem(R.id.nav_savedcal);
mDrawerLayout.closeDrawers();
fragmentTransaction=getSupportFragmentManager().beginTransaction();
fragmentTransaction.replace(R.id.main_content, new savedFragment());
fragmentTransaction.commit();
getSupportActionBar().setTitle(("Saved Calculations"));
item.setChecked(true);
break;
case R.id.nav_upldoc:
navigationView.getMenu().getItem(0).setChecked(false);
navigationView.getMenu().getItem(1).setChecked(false);
navigationView.getMenu().getItem(3).setChecked(false);
navigationView.setCheckedItem(R.id.nav_upldoc);
mDrawerLayout.closeDrawers();
fragmentTransaction=getSupportFragmentManager().beginTransaction();
fragmentTransaction.replace(R.id.main_content, new uploadedfragment());
fragmentTransaction.commit();
getSupportActionBar().setTitle(("Uploaded documents"));
item.setChecked(true);
break;
case R.id.nav_site:
navigationView.getMenu().getItem(0).setChecked(false);
navigationView.getMenu().getItem(1).setChecked(false);
navigationView.getMenu().getItem(2).setChecked(false);
navigationView.setCheckedItem(R.id.nav_site);
mDrawerLayout.closeDrawers();
fragmentTransaction=getSupportFragmentManager().beginTransaction();
fragmentTransaction.replace(R.id.main_content, new resultsite());
fragmentTransaction.commit();
getSupportActionBar().setTitle(("VTU Results"));
item.setChecked(true);
break;
}
return false;
}
});
}
public boolean onOptionsItemSelected(MenuItem item ){
if(mToggle.onOptionsItemSelected(item)){
return true;
}
return super.onOptionsItemSelected(item);
}
#Override
public void onBackPressed() {
DialogInterface.OnClickListener dialogClickListener = new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
switch (which) {
case DialogInterface.BUTTON_POSITIVE: {
finish();
}
break;
case DialogInterface.BUTTON_NEGATIVE:
break;
}
}
};
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setMessage("Are you sure you want to exit?").setPositiveButton("Yes", dialogClickListener)
.setNegativeButton("No", dialogClickListener).show();
return;
}
}
This is my default fragment :
public class mainfrag extends Fragment {
private View view;
private AdView adView;
private Button button10;
private Button button11;
public mainfrag() {
// Required empty public constructor
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
view = inflater.inflate(R.layout.fragment_mainfrag, container, false);
adView = view.findViewById(R.id.adView);
button10 = (Button) view.findViewById(R.id.button10);
button10.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
openmainactivity();
}
});
button11 = (Button) view.findViewById(R.id.button11);
button11.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
openscheme();
}
});
return view;
}
public void openmainactivity() {
Intent intent = new Intent(getContext(), MainActivity.class);
startActivity(intent);
}
public void openscheme(){
Intent intent=new Intent(getContext(), scheme.class);
startActivity(intent);
}
}
This is one of the other fragments:
public class savedFragment extends Fragment {
RecyclerView recyclerview;
adapter_sgpa recyclerAdapter;
ArrayList<POJO> sgpaArrayList;
public savedFragment() {
// Required empty public constructor
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
FragmentTransaction tx = getChildFragmentManager().beginTransaction();
tx.replace(R.id.container, new sgpa_frag());
tx.commit();
}
private BottomNavigationView.OnNavigationItemSelectedListener mOnNavigationItemSelectedListener
= new BottomNavigationView.OnNavigationItemSelectedListener() {
#Override
public boolean onNavigationItemSelected(#NonNull MenuItem item) {
int id = item.getItemId();
Fragment fragment = null;
switch (id) {
case R.id.navigation_sgpa:
sgpa_frag sf = new sgpa_frag();
FragmentManager fragmentManager = getChildFragmentManager();
fragmentManager.beginTransaction().replace(R.id.container, sf).commit();
return true;
case R.id.navigation_cgpa:
cgpa_frag cf = new cgpa_frag();
fragmentManager = getChildFragmentManager();
fragmentManager.beginTransaction().replace(R.id.container, cf).commit();
return true;
}
return false;
}
};
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
final View v = inflater.inflate(R.layout.fragment_saved, container, false);
BottomNavigationView nav = (BottomNavigationView) v.findViewById(R.id.bottom_navigation);
nav.setOnNavigationItemSelectedListener(mOnNavigationItemSelectedListener);
return v;
}
}
What changes should I make in this code so that I am able to move back from the other fragments to the main fragment on pressing back button ?
Maintain one boolean variable to check current fragment is MainFragment or not.
if its not MainFragment -> replace MainFragment
Else -> super.onBackPressed()
ex:
private boolean isMainFragment=true; //make it false when move to other fragment
#Override
public void onBackPressed() {
if(!isMainFragment){
isMainFragment=true;
//replace your MainFragment
}
else{
//your logic show dialog or super.onBackPressed()
}
}
Ithink I know what you need. have a look at the last part of this documentation
"You can add a fragment transaction to the back stack. The back stack keeps track of actions in your app which can be backtracked when the user clicks Android's standard "back" button on the device. If you add a fragment transaction to the back stack then the transaction can be backtracked (reversed) with a click on the back button on the device" quotet from Jenkov
simply do fragmentTransaction.addToBackStack(null) on your main activity before you do the commit this will allow you to travel back using the back button
if you always want to travel back to the main fragment then you want to only add the main fragment to the backstack that way on pressing the back button you will always land there
in this part of your oncreate:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_what);
mDrawerLayout=(DrawerLayout)findViewById(R.id.drawer_layout);
mToggle=new ActionBarDrawerToggle(this, mDrawerLayout, R.string.open, R.string.close);
mDrawerLayout.addDrawerListener(mToggle);
mToggle.syncState();
fragmentTransaction= getSupportFragmentManager().beginTransaction();
fragmentTransaction.add(R.id.main_content,new mainfrag());
//HERE YOU PUT THE CODE V
fragmentTransaction.addToBackStack(null);
//HERE YOU PUT THE CODE ^
fragmentTransaction.commit();
ActionBar actionBar= getSupportActionBar();
actionBar.setDisplayHomeAsUpEnabled(true);
// ALL THE OTHER STUFF COMMING AFTER

Action Bar Items are clickable, but do not respond to events in a Fragment

Basically my project have to have different toolbars, one for each fragment switched by the bottom navigation bar.
The fragment toolbars items are clickable, when I long press, shows the title item etc, but they don't perform the action. For example, When I set to show a toast when click on that item, he'll not perform. Any Suggestion? Thanks.
public class FeedFragment extends Fragment {
public static final String TAG = "Tag Free";
DialogFragment mDialog;
FloatingActionButton fab;
RevealFrameLayout reveal;
FrameLayout frame;
private ConstraintLayout layoutDialog;
boolean isOpen = false;
public FeedFragment() {
// Required empty public constructor
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setHasOptionsMenu(true);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_feed, container, false);
/** Toolbar **/
Toolbar myToolbar = (Toolbar) view.findViewById(R.id.my_toolbar);
((AppCompatActivity) getActivity()).setSupportActionBar(myToolbar);
ActionBar ab = ((AppCompatActivity) getActivity()).getSupportActionBar();
ab.setDisplayHomeAsUpEnabled(false);
// navigation bottom
fab = getActivity().findViewById(R.id.fab_button);
fab.setImageDrawable(getResources().getDrawable(R.drawable.ic_pencil_black_24dp));
fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
FragmentTransaction ft = getFragmentManager().beginTransaction().setCustomAnimations(R.anim.hold, R.anim.slide_down);
Fragment prev = getFragmentManager().findFragmentByTag("dialog");
if (prev != null) {
ft.remove(prev);
}
ft.addToBackStack(null);
DialogFragment dialogFragment = new PostDialog();
dialogFragment.show(ft, "dialog");
dialogFragment.setStyle(DialogFragment.STYLE_NORMAL, R.style.DialogFragmentTheme);
}
});
return view;
}
#Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
inflater.inflate(R.menu.appbar_feed, menu);super.onCreateOptionsMenu(menu, inflater);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.action_personProfile:
Toast.makeText(getActivity(),"not responding",Toast.LENGTH_SHORT).show();
Intent intent = new Intent(getActivity(), MyUserProfileActivity.class);
startActivity(intent);
return true;
case R.id.action_settings:
Toast.makeText(getActivity(),"not responding",Toast.LENGTH_SHORT).show();
return true;
default:
// If we got here, the user's action was not recognized.
// Invoke the superclass to handle it.
return super.onOptionsItemSelected(item);
}
}
}
You are not chaining to the superclass in the activity methods.
Refactor your code as below :
#Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
inflater.inflate(R.menu.appbar_feed, menu);
super.onCreateOptionsMenu(menu, inflater);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.action_personProfile:
Toast.makeText(getActivity(),"not responding",Toast.LENGTH_SHORT).show();
Intent intent = new Intent(getActivity(), MyUserProfileActivity.class);
startActivity(intent);
break;
case R.id.action_settings:
Toast.makeText(getActivity(),"not responding",Toast.LENGTH_SHORT).show();
break;
default:
// If we got here, the user's action was not recognized.
// Invoke the superclass to handle it.
break;
}
return super.onOptionsItemSelected(item);
}
Hope now your code will work fine.

Android home button with drawer navigation stops to work with rotation screen

I have a main activity with navigation drawer and a button to load fragment.
When the main ativity is launched I load the MainFragment.
In this moment all works well. The hamburger icon is showing and my Main fragment was loaded.
Next, I click a button and load a secondFragment. After I load the second fragment, I can use the backbutton and homebutton to come back to main activity without problems.
When I am with second fragment loaded and I make a rotation screen, the back button continues to work well, but the home button disappears and hamburger icon appears.
What am i doing wrong?
public class MainActivity extends AppCompatActivity {
private ActionBarDrawerToggle actionBarDrawerToggle;
private DrawerLayout drawerLayout;
private Toolbar toolbar;
private CharSequence mDrawerTitle;
private CharSequence mTitle;
private String mSubTitle;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
initNavigationDrawer();
if (savedInstanceState != null) {
return;
}
MainActivityFragment mainFragment = new MainActivityFragment();
firstFragment.setArguments(getIntent().getExtras());
// Add the fragment to the 'fragment_container' FrameLayout
FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
//transaction.replace(R.id.fragment_container, firstFragment);
transaction.replace(R.id.fragment_container, mainFragment, "princ");
transaction.commit();
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Only handle with DrawerToggle if the drawer indicator is enabled.
if (actionBarDrawerToggle.isDrawerIndicatorEnabled() &&
actionBarDrawerToggle.onOptionsItemSelected(item)) {
return true;
}
// Handle your other action bar items...
return super.onOptionsItemSelected(item);
}
}
public Fragment getCurrentFragment(){
FragmentManager frgmgr = getSupportFragmentManager();
return frgmgr.findFragmentById(R.id.fragment_container);
}
#Override
public void onBackPressed() {
if (drawerLayout != null) {
if (drawerLayout.isDrawerOpen(GravityCompat.START)) {
drawerLayout.closeDrawer(GravityCompat.START);
return;
}
}
if ((getCurrentFragment() instanceof MainFragment)) {
finish();
} else if (getSupportFragmentManager().getBackStackEntryCount() > 0) {
getSupportFragmentManager().popBackStack();
} else super.onBackPressed();
}
public void initNavigationDrawer() {
NavigationView navigationView = (NavigationView) findViewById(R.id.navigation_view);
navigationView.setNavigationItemSelectedListener(new NavigationView.OnNavigationItemSelectedListener() {
#Override
public boolean onNavigationItemSelected(MenuItem menuItem) {
FragmentManager frgmgr = getSupportFragmentManager();
FragmentTransaction transaction = frgmgr.beginTransaction();
Fragment cur_frag;
// Handle navigation view item clicks here.
int id = menuItem.getItemId();
switch (id) {
case R.id.home:
cur_frag = frgmgr.findFragmentById(R.id.fragment_container);
if (!(cur_frag instanceof MainActivityFragment)) {
MainActivityFragment frag = new MainActivityFragment();
transaction.setCustomAnimations(R.anim.enter_from_left, R.anim.exit_to_right, R.anim.enter_from_right, R.anim.exit_to_left);
transaction.replace(R.id.fragment_container, frag);
transaction.commit();
break;
}
drawerLayout.closeDrawers();
break;
case R.id.logout_drw:
finish();
}
drawerLayout.closeDrawer(GravityCompat.START);
return true;
}
});
View header = navigationView.getHeaderView(0);
TextView tv_email = (TextView) header.findViewById(R.id.tv_email);
tv_email.setText("Agendamento");
drawerLayout = (DrawerLayout) findViewById(R.id.drawer);
mTitle = mDrawerTitle = getTitle();
actionBarDrawerToggle = new ActionBarDrawerToggle(this, drawerLayout, toolbar, R.string.drawer_open, R.string.drawer_close) {
#Override
public void onDrawerClosed(View v) {
super.onDrawerClosed(v);
}
#Override
public void onDrawerOpened(View v) {
super.onDrawerOpened(v);
}
};
drawerLayout.addDrawerListener(actionBarDrawerToggle);
actionBarDrawerToggle.syncState();
if (toolbar != null) {
getSupportFragmentManager().addOnBackStackChangedListener(new FragmentManager.OnBackStackChangedListener() {
#Override
public void onBackStackChanged() {
int i=getSupportFragmentManager().getBackStackEntryCount();
if ((i > 0) || (!(getCurrentFragment() instanceof MainActivityFragment))) {
getSupportActionBar().setDisplayHomeAsUpEnabled(true); // show back button
toolbar.setNavigationOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
onBackPressed();
}
});
} else {
getSupportActionBar().setDisplayHomeAsUpEnabled(false);
actionBarDrawerToggle.syncState();
toolbar.setNavigationOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
drawerLayout.openDrawer(GravityCompat.START);
}
});
}
}
});
}
}
}
Main Fragment:
public class MainFragment extends Fragment {
public MainFragment() {
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view=inflater.inflate(R.layout.fragment_main, container, false);
Button butCons= (Button) view.findViewById(R.id.butcons);
butCons.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
SecundaryFrag frag = new SecundaryFragFrag();
// Add the fragment to the 'fragment_container' FrameLayout
FragmentTransaction transaction=getFragmentManager().beginTransaction();
transaction.setCustomAnimations(R.anim.enter_from_left, R.anim.exit_to_right, R.anim.enter_from_right, R.anim.exit_to_left);
transaction.replace(R.id.fragment_container, frag);
transaction.addToBackStack(null);
transaction.commit();
}
});
return view;
}
}
Secondary Fragment:
public class SecundaryFrag extends Fragment{
public SecundaryFrag() {
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
View view=inflater.inflate(R.layout.fragment_consulta_ag, container, false);
return view;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home:
((MainActivity)getActivity()).onBackPressed();
return true;
default:
return super.onOptionsItemSelected(item);
}
}
}
After Rotation:
Main activty with main fragment:
Before Rotation:
I believe it is related to the fact that the view is recreated after the orientation change. I would take a closer look to the onCreate() from the MainActivity in particular when the
if (savedInstanceState != null) {
return;
}
is triggered.
One option is to retain the fragments and restoring them onCreate. Also you could turn off the recreation by catching the orientation and handle it yourself in the application, you can see here both options explained developer.android.com/guide/topics/resources/

Why not works ClickListeners for Toolbar?

I use MaterialDrawer and code MainActivity is:
public class MainActivity extends AppCompatActivity implements KitchenFragment.CallbackOne {
public static final String TAG = "myLogTag";
private Toolbar mToolbar;
private Drawer drawer;
private FragmentManager fm;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mToolbar = (Toolbar) findViewById(R.id.toolbar);
mToolbar.setNavigationOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Log.d(TAG, "CLICK NOCL");
}
});
setSupportActionBar(mToolbar);
// getSupportActionBar().setDisplayHomeAsUpEnabled(false);
fm = getFragmentManager();
Fragment fragment = fm.findFragmentById(R.id.content_frame);
if (fragment == null) {
fragment = MenuFragment.newInstance();
fm.beginTransaction()
.add(R.id.content_frame, fragment)
.commit();
}
drawer = new DrawerBuilder()
.withActivity(this)
.withToolbar(mToolbar)
.withActionBarDrawerToggle(true)
.withHeader(R.layout.drawer_header)
.addDrawerItems(
new PrimaryDrawerItem().withName(R.string.menu).withIdentifier(1),
new PrimaryDrawerItem().withName(R.string.kitchen_title).withIdentifier(2),
new PrimaryDrawerItem().withName(R.string.information_title).withEnabled(false)
).withOnDrawerItemClickListener(new Drawer.OnDrawerItemClickListener() {
#Override
public boolean onItemClick(View view, int position, IDrawerItem drawerItem) {
Log.d(TAG, "position clicked: " + position);
Fragment fragment = MenuFragment.newInstance();
switch (position) {
case 1:
fragment = MenuFragment.newInstance();
break;
case 2:
fragment = KitchenFragment.newInstance();
break;
default:
fragment = new Fragment();
}
fm.beginTransaction().replace(R.id.content_frame, fragment).commit();
return false;
}
})
.withFireOnInitialOnClick(true)
.withSavedInstance(savedInstanceState)
.withOnDrawerNavigationListener(new Drawer.OnDrawerNavigationListener() {
#Override
public boolean onNavigationClickListener(View view) {
Log.d(TAG, "CLICK in DNL");
if (!drawer.getActionBarDrawerToggle().isDrawerIndicatorEnabled()) {
onBackPressed();
return true;
} else
return false;
}
})
.build();
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.menu_menu, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
Log.d(TAG, "CLICK OIS");
switch (item.getItemId()) {
case R.id.action_settings:
return true;
case android.R.id.home:
getFragmentManager().popBackStackImmediate();
return true;
default:
return super.onOptionsItemSelected(item);
}
}
#Override
protected void onSaveInstanceState(Bundle outState) {
outState = drawer.saveInstanceState(outState);
super.onSaveInstanceState(outState);
}
#Override
public void onBackPressed() {
if (drawer.isDrawerOpen())
drawer.closeDrawer();
else if (getFragmentManager().getBackStackEntryCount() == 1) {
getSupportActionBar().setDisplayHomeAsUpEnabled(false);
drawer.getActionBarDrawerToggle().syncState();
getFragmentManager().popBackStack();
} else if (getFragmentManager().getBackStackEntryCount() > 0)
getFragmentManager().popBackStack();
else
super.onBackPressed();
}
#Override
public void setFirstSelected() {
drawer.setSelection(1);
}
}
I'm trying to trace a Click in mToolbar.setNavigationOnClickListener
and withOnDrawerNavigationListener and onOptionsItemSelected.
None of the listeners not reacted for clicking.
How you see i use Activity that launches Fragment (1), which in turn lets Fragment (2 and 3). In 2 and 3 Fragment in OnCreate i use ((AppCompatActivity)getActivity()).getSupportActionBar().setDisplayHomeAsUpEnabled(true); , and I need to by pressing the back button (in toolbar), returning the previous fragment, and not open Drawer
The MaterialDrawer already handles all the listeners for you. If you need to do an action after the drawer opens or closes you can provide the listener via the DrawerBuilder
For the icon you have this listener:
OnDrawerNavigationListener
https://github.com/mikepenz/MaterialDrawer/blob/develop/library/src/main/java/com/mikepenz/materialdrawer/DrawerBuilder.java#L1158
For drawer close / open this listener:
OnDrawerListener
https://github.com/mikepenz/MaterialDrawer/blob/develop/library/src/main/java/com/mikepenz/materialdrawer/DrawerBuilder.java#L1116
I suggest you to create new Activity using android studio wizard. File->New->Activity->Navigation Drawer Activity.
In that case ActionBarDrawerToaggle is used
ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
This toggle contains click listener which handle open/close drawer functionality for you.
Also you can that item clicks implemented through OnNavigationItemSelectedListener.onNavigationItemSelected(MenuItem item)

Categories

Resources