I will try to explain at best, adding references and images in which
I think it is difficult to explain in words the error I encountered.
Working with the fragments and the Navigation Drawer I've faced this
bug:
From time to time, when I open the navigation menu, the previous
fragment is duplicated or loaded again. This thing is completely
random, without a precise scheme. The only thing that seems
connected is the RecyclerView and the Navigation Drawer.
Just because I do not know where I'm wrong, write in the comments if you
need something, code or other information and from time to time I'll add it
to the original question.
I am not receiving any errors and to help both me and you add some code and
images of how that fragment is loaded without bugs:
#Override
public boolean onNavigationItemSelected(MenuItem item) {
Fragment fragment = null;
Class aclass = null;
Bundle args = new Bundle();
Intent intentOperatore = getIntent();
String mParamOperatore = intentOperatore.getStringExtra(ARG_PARAM_OPERATORE);
boolean navigation = Boolean.FALSE;
boolean intent = Boolean.FALSE;
boolean scan = Boolean.FALSE;
boolean exit = Boolean.FALSE;
try{
switch (item.getItemId()){
case R.id.nav_home:
aclass = HomeFragment.class;
fragment = (Fragment) aclass.newInstance();
args.putString(ARG_PARAM_OPERATORE,mParamOperatore);
fragment.setArguments(args);
navigation = Boolean.TRUE;
break;
case R.id.nav_procedura_immobiliare:
aclass = FiltroFragment.class;
fragment = (Fragment) aclass.newInstance();
args.putString(ARG_CHECK_CLASS,"immobiliari");
fragment.setArguments(args);
navigation = Boolean.TRUE;
break;
case R.id.nav_procedura_mobiliare:
aclass = FiltroFragment.class;
fragment = (Fragment) aclass.newInstance();
args.putString(ARG_CHECK_CLASS,"mobiliari");
fragment.setArguments(args);
navigation = Boolean.TRUE;
break;
case R.id.nav_localizza_procedura:
aclass = LocalizzaActivity.class;
intent = Boolean.TRUE;
break;
case R.id.nav_ricognizione:
aclass = RicognizioneFragment.class;
fragment = (Fragment) aclass.newInstance();
args.putString(ARG_PARAM_RICOGNIZIONE,""); //TODO: Add param here.
fragment.setArguments(args);
navigation = Boolean.TRUE;
break;
case R.id.nav_qrcode:
scan = Boolean.TRUE;
break;
case R.id.nav_exit:
exit = Boolean.TRUE;
break;
}
if(navigation) { // Navigazione per i fragment
FragmentManager fragmentManager = getSupportFragmentManager();
fragmentManager.beginTransaction().replace(R.id.flContent, fragment).commit();
} if(intent) { // Navigazione per le activity
Intent myIntent = new Intent(getApplicationContext(),aclass);
myIntent.putExtra(ARG_PARAM_OPERATORE,mParamOperatore);
startActivity(myIntent);
finish();
} if(scan) {
new MVBarcodeScanner.Builder()
.setScanningMode(MVBarcodeScanner.ScanningMode.SINGLE_AUTO)
.setFormats(Barcode.QR_CODE)
.build()
.launchScanner(MainActivity.this,REQ_CODE);
} if(exit) { // Navigazione per l'uscita
MaterialDialog dialog = new MaterialDialog.Builder(this)
.title(R.string.title_exit)
.content(R.string.summary_exit)
.positiveText(R.string.action_exit)
.onPositive(new MaterialDialog.SingleButtonCallback() {
#Override
public void onClick(MaterialDialog dialog, DialogAction which) {
finish();
}
})
.negativeText(R.string.action_no)
.show();
}
} catch (Exception e) {
Log.e(this.getClass().getName(), e.getMessage(), e);
}
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
drawer.closeDrawer(GravityCompat.START);
return true;
}
Edit:
I also notice another thing that recycling is not the only thing to
duplicate. There is also the toolbar item that is duplicated:
Edit 2:
- I've added the onCreateOptionsMenu and some code that i run in the
onCreateView:
#Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
//inflater.inflate(R.menu.procedura_menu_action, menu);
inflater.inflate(R.menu.procedura_menu_list, menu);
super.onCreateOptionsMenu(menu, inflater);
}
#Override
public View onCreateView(#NonNull LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_procedure_list, container, false);
Context context = view.getContext();
setHasOptionsMenu(true);
recyclerView = (RecyclerView) view.findViewById(R.id.rvProcedure);
RecyclerView.LayoutManager mLayoutManager = new LinearLayoutManager(context);
mAdapter = new ProcedureAdapter(context,procedure,this);
recyclerView.setLayoutManager(mLayoutManager);
recyclerView.setItemAnimator(new DefaultItemAnimator());
recyclerView.addItemDecoration(new DividerItemDecoration(context,LinearLayoutManager.VERTICAL));
recyclerView.setAdapter(mAdapter);
actionModeCallback = new ActionModeCallback();
Toolbar toolbar = view.findViewById(R.id.toolbar);
toolbar.setTitle(getString(R.string.title_lista_procedure) + " " + mCheckClass);
toolbar.setNavigationIcon(R.drawable.ic_menu_navigator);
((AppCompatActivity)getActivity()).setSupportActionBar(toolbar);
toolbar.setNavigationOnClickListener( new View.OnClickListener() {
public void onClick(View v) {
DrawerLayout drawerLayout = (DrawerLayout) getActivity().findViewById(R.id.drawer_layout);
if(drawerLayout.isDrawerOpen(GravityCompat.START)){
drawerLayout.closeDrawer(GravityCompat.START);
} else {
drawerLayout.openDrawer(GravityCompat.START);
}
}
});
floatingActionButton = (FloatingActionButton) view.findViewById(R.id.fab_new);
floatingActionButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
args.putString(ARG_PARAM_TIPOLOGIA,mParamTipologia); //Passa la procedura selezionata se siamo in modifica
args.putString(ARG_PARAM_PROCEDURA,new Gson().toJson(procedure.get(lastPosition)));
if(actionMode != null) //Leva la selezione se è presente, prima di passare ad un'altro fragment.
enableActionMode(lastPosition);
try {
if ((getActivity()) != null) {
FragmentManager fragmentManager = ((AppCompatActivity)getActivity()).getSupportFragmentManager();
Class fragmentClass = ProceduraFragment.class;
Fragment fragment = (Fragment) fragmentClass.newInstance();
fragment.setArguments(args);
fragmentManager.beginTransaction().replace(R.id.flContent, fragment).addToBackStack(null).commit();
}
} catch (java.lang.InstantiationException | IllegalAccessException e) {
e.printStackTrace();
}
}
});
//TODO: Implements here the load logic for procedure.
if(mParamProcedura != null && !(procedure.size() > 0)) {
procedure.add(mParamProcedura);
} else if(!(procedure.size() > 0)) {
refreshList(AlphaMAS.getData());
}
return view;
}
Why create a new fragment instance everytime? Try something like this:
if (fragment == null)
fragment = (Fragment) aclass.newInstance();
Inside your layout in both Fragments use this :
android:clickable="true"
android:focusable="true"
Solution
Set background to both of your xml file's parent layout.
android:background="#color/background_color_which_you_want"
Edit 1:
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.procedura_menu_list, menu);
return super.onCreateOptionsMenu(menu);
}
Related
I have created a main activity which has a fragment container in it, I am replacing many fragments in it on navigation menu option select. Its working fine, but the problem is:
When I click a navigation item twice, two identical fragments open, i have to press the back button twice to go back.
When all fragments are destroyed after pressing back, I see an empty page (which may be main activity page I guess).
layout_main.xml
<?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/main_activity_page"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#color/pageBackgroundColor"
tools:context="co.sd.app.MainActivity">
<RelativeLayout
android:id="#+id/fragment_container"
android:layout_width="match_parent"
android:layout_height="match_parent" />
<android.support.design.widget.NavigationView
android:id="#+id/side_nav_drawer"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:layout_gravity="start"
android:padding="0sp"
app:menu="#menu/side_navigation_menu" />
</android.support.v4.widget.DrawerLayout>
MainActivity.java
public class MainActivity extends AppCompatActivity {
private Bundle bundle;
private SessionManager session;
private DrawerLayout drawerLayout;
private ActionBarDrawerToggle actionBarToggle;
private TextView cartItemCountDisplay;
private NavigationView sideNavView;
private Menu sideNavViewMenu;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
drawerLayout = (DrawerLayout) findViewById(R.id.main_activity_page);
actionBarToggle = new ActionBarDrawerToggle(this, drawerLayout, R.string.OPEN, R.string.CLOSE);
drawerLayout.addDrawerListener(actionBarToggle);
actionBarToggle.syncState();
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
bundle = new Bundle();
sideNavView = ((NavigationView) findViewById(R.id.side_nav_drawer));
sideNavViewMenu = sideNavView.getMenu();
//To Display Home Fragment On Page Load
displaySelectedItemResult(sideNavViewMenu.findItem(R.id.nav_home));
//To Adjust Login or Logout option in side navigation menu
if (session.isUserLoggedIn()) {
sideNavViewMenu.findItem(R.id.nav_login).setVisible(false);
sideNavViewMenu.findItem(R.id.nav_logout).setVisible(true);
} else {
sideNavViewMenu.findItem(R.id.nav_login).setVisible(true);
sideNavViewMenu.findItem(R.id.nav_logout).setVisible(false);
}
//Operation on side navigation item click
sideNavView.setNavigationItemSelectedListener(new NavigationView.OnNavigationItemSelectedListener() {
#Override
public boolean onNavigationItemSelected(MenuItem item) {
displaySelectedItemResult(item);
//navDrawerLayout.closeDrawers();
return true;
}
});
}
private void displaySelectedItemResult(MenuItem item) {
sideNavViewMenu.findItem(R.id.nav_home).setChecked(false);
sideNavViewMenu.findItem(R.id.nav_contactUs).setChecked(false);
sideNavViewMenu.findItem(R.id.nav_aboutUs).setChecked(false);
sideNavViewMenu.findItem(R.id.nav_login).setChecked(false);
sideNavViewMenu.findItem(R.id.nav_logout).setChecked(false);
Fragment fragment;
switch (item.getItemId()) {
case R.id.nav_user:
if (session.isUserLoggedIn()) {
item.setTitle(session.getUserDetails().get(SessionManager.KEY_NAME));
} else {
item.setTitle("Login First!");
}
drawerLayout.closeDrawer(GravityCompat.START);
break;
case R.id.nav_home:
fragment = new HomeFragment();
if (fragment != null) {
callNavMenuItemsFragment(fragment, "FRAG_HOME");
}
item.setChecked(true);
drawerLayout.closeDrawer(GravityCompat.START);
break;
case R.id.nav_contactUs:
fragment = new ContactUsFragment();
if (fragment != null) {
callNavMenuItemsFragment(fragment, "FRAG_CONTACT_US");
}
item.setChecked(true);
drawerLayout.closeDrawer(GravityCompat.START);
break;
case R.id.nav_aboutUs:
fragment = new AboutUsFragment();
if (fragment != null) {
callNavMenuItemsFragment(fragment, "FRAG_ABOUT_US");
}
item.setChecked(true);
drawerLayout.closeDrawer(GravityCompat.START);
break;
case R.id.nav_login:
new UserAuthentication(MainActivity.this, session).loginAndSignupDialog();
sideNavViewMenu.findItem(R.id.nav_login).setVisible(false);
sideNavViewMenu.findItem(R.id.nav_logout).setVisible(true);
item.setChecked(true);
drawerLayout.closeDrawer(GravityCompat.START);
break;
case R.id.nav_logout:
session.logoutUser();
sideNavViewMenu.findItem(R.id.nav_login).setVisible(true);
sideNavViewMenu.findItem(R.id.nav_logout).setVisible(false);
item.setChecked(true);
drawerLayout.closeDrawer(GravityCompat.START);
break;
default:
}
}
private FragmentTransaction callNavMenuItemsFragment(final Fragment fragment, final String fragmentTag) {
FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
ft.addToBackStack(null);
//if (!ACTIVE_FRAGMENT_ID.equals(String.valueOf(fragment.getId()))) {
if (!activeFragmentIDsList.contains(String.valueOf(fragment.getId()))) {
ft.replace(R.id.fragment_container, fragment, fragmentTag);
activeFragmentIDsList.add(String.valueOf(fragment.getId()));
}
ft.commit();
return ft;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
if (actionBarToggle.onOptionsItemSelected(item)) {
return true;
}
switch (item.getItemId()) {
case android.R.id.home:
finish();
break;
case R.id.cart:
if (session.isUserLoggedIn()) {
startActivity(new Intent(MainActivity.this, CartActivity.class));
} else if (new UserAuthentication(MainActivity.this, session).loginAndSignupDialog()) {
startActivity(new Intent(MainActivity.this, CartActivity.class));
}
break;
default:
}
return super.onOptionsItemSelected(item);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.actionbar_menu, menu);
final MenuItem menuItem = menu.findItem(R.id.cart);
MenuItemCompat.setActionView(menuItem, R.layout.cart_badge_layout);
final View actionView = MenuItemCompat.getActionView(menuItem);
cartItemCountDisplay = actionView.findViewById(R.id.cart_badge);
setupBadge();
actionView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
setupBadge();
onOptionsItemSelected(menuItem);
}
});
return super.onCreateOptionsMenu(menu);
}
private void setupBadge() {
int itemCount = (((AppGlobalContent) getApplicationContext()).getSelectedItemsCount());
if (cartItemCountDisplay != null) {
if (itemCount == 0) {
if (cartItemCountDisplay.getVisibility() != View.GONE) {
cartItemCountDisplay.setVisibility(View.GONE);
}
} else {
cartItemCountDisplay.setText(String.valueOf(Math.min(itemCount, 99)));
if (cartItemCountDisplay.getVisibility() != View.VISIBLE) {
cartItemCountDisplay.setVisibility(View.VISIBLE);
}
}
}
}
#Override
public void onBackPressed() {
if (drawerLayout.isDrawerOpen(GravityCompat.START)) {
drawerLayout.closeDrawer(GravityCompat.START);
} else {
super.onBackPressed();
}
}
}
Please suggest me on this.
This will fix your second problem, when you add fragments to your container they will be add to the stack,
if (getSupportFragmentManager().getBackStackEntryCount() == 1) {
finish();
}
else {
super.onBackPressed();
}
so when the stack entry count is 1 you have to finish the activity.
For the first problem you have to use "pop back stack" while adding the same fragment again use : getSupportFragmentManager().popBackStack();
I have some slides with ViewPager that shows application help and I want to show it in DrawerLayout too.
this is HelpActivity.class:
public class HelpActivity extends Activity {
private ViewPager viewPager;
private MyViewPagerAdapter myViewPagerAdapter;
private LinearLayout dotsLayout;
private TextView[] dots;
private int[] layouts;
private Button btnSkip, btnNext;
private PrefManager prefManager;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// Checking for first time launch - before calling setContentView()
prefManager = new PrefManager(this);
if (!prefManager.isFirstTimeLaunch()) {
launchHomeScreen();
finish();
}
// Making notification bar transparent
if (Build.VERSION.SDK_INT >= 21) {
getWindow().getDecorView().setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_STABLE | View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN);
}
setContentView(R.layout.fragment_help);
viewPager = (ViewPager) findViewById(R.id.view_pager);
dotsLayout = (LinearLayout) findViewById(R.id.layoutDots);
btnSkip = (Button) findViewById(R.id.btn_skip);
btnNext = (Button) findViewById(R.id.btn_next);
// layouts of all welcome sliders
// add few more layouts if you want
layouts = new int[]{
R.layout.welcome_1,
R.layout.welcome_2,
R.layout.welcome_3,
R.layout.welcome_4,
R.layout.welcome_5,
R.layout.welcome_6,
R.layout.welcome_7};
// adding bottom dots
addBottomDots(0);
// making notification bar transparent
changeStatusBarColor();
myViewPagerAdapter = new MyViewPagerAdapter();
viewPager.setAdapter(myViewPagerAdapter);
viewPager.addOnPageChangeListener(viewPagerPageChangeListener);
btnSkip.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
launchHomeScreen();
}
});
btnNext.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// checking for last page
// if last page home screen will be launched
int current = getItem(+1);
if (current < layouts.length) {
// move to next screen
viewPager.setCurrentItem(current);
} else {
launchHomeScreen();
}
}
});
}
private void addBottomDots(int currentPage) {
dots = new TextView[layouts.length];
int[] colorsActive = getResources().getIntArray(R.array.array_dot_active);
int[] colorsInactive = getResources().getIntArray(R.array.array_dot_inactive);
dotsLayout.removeAllViews();
for (int i = 0; i < dots.length; i++) {
dots[i] = new TextView(this);
dots[i].setText(Html.fromHtml("•"));
dots[i].setTextSize(35);
dots[i].setTextColor(colorsInactive[currentPage]);
dotsLayout.addView(dots[i]);
}
if (dots.length > 0)
dots[currentPage].setTextColor(colorsActive[currentPage]);
}
private int getItem(int i) {
return viewPager.getCurrentItem() + i;
}
private void launchHomeScreen() {
prefManager.setFirstTimeLaunch(false);
startActivity(new Intent(HelpActivity.this, MainActivity.class));
finish();
}
// viewpager change listener
ViewPager.OnPageChangeListener viewPagerPageChangeListener = new ViewPager.OnPageChangeListener() {
#Override
public void onPageSelected(int position) {
addBottomDots(position);
// changing the next button text 'NEXT' / 'GOT IT'
if (position == layouts.length - 1) {
// last page. make button text to GOT IT
btnNext.setText(/*getString(R.string.start)*/ "Start");
btnSkip.setVisibility(View.GONE);
} else {
// still pages are left
btnNext.setText(/*getString(R.string.next)*/ "Next");
btnSkip.setVisibility(View.VISIBLE);
}
}
#Override
public void onPageScrolled(int arg0, float arg1, int arg2) {
}
#Override
public void onPageScrollStateChanged(int arg0) {
}
};
/**
* Making notification bar transparent
*/
private void changeStatusBarColor() {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
Window window = getWindow();
window.addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS);
window.setStatusBarColor(Color.TRANSPARENT);
}
}
/**
* View pager adapter
*/
public class MyViewPagerAdapter extends PagerAdapter {
private LayoutInflater layoutInflater;
public MyViewPagerAdapter() {
}
#Override
public Object instantiateItem(ViewGroup container, int position) {
layoutInflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View view = layoutInflater.inflate(layouts[position], container, false);
container.addView(view);
return view;
}
#Override
public int getCount() {
return layouts.length;
}
#Override
public boolean isViewFromObject(View view, Object obj) {
return view == obj;
}
#Override
public void destroyItem(ViewGroup container, int position, Object object) {
View view = (View) object;
container.removeView(view);
}
}
}
this is PrefManager.class:
public class PrefManager {
SharedPreferences pref;
SharedPreferences.Editor editor;
Context _context;
// shared pref mode
int PRIVATE_MODE = 0;
// Shared preferences file name
private static final String PREF_NAME = "stand up-welcome";
private static final String IS_FIRST_TIME_LAUNCH = "IsFirstTimeLaunch";
public PrefManager(Context context) {
this._context = context;
pref = _context.getSharedPreferences(PREF_NAME, PRIVATE_MODE);
editor = pref.edit();
}
public void setFirstTimeLaunch(boolean isFirstTime) {
editor.putBoolean(IS_FIRST_TIME_LAUNCH, isFirstTime);
editor.commit();
}
public boolean isFirstTimeLaunch() {
return pref.getBoolean(IS_FIRST_TIME_LAUNCH, true);
}
}
and I use this code for defining it to drawerLayout:
public void selectDrawerItem(MenuItem menuItem) {
if (menuItem.getItemId()== R.id.nav_item_help) {
//startActivityForResult(new Intent(this,HelpActivity.class),1000);
startActivity(new Intent(MainActivity.this,HelpActivity.class));
}
with clicking on help in drawer, nothing shows. what should I do?
This is MainActivity.class:
ublic class MainActivity extends AppCompatActivity {
public DrawerLayout drawerLayout;
public Toolbar toolbar;
public NavigationView navigationView;
public ActionBarDrawerToggle actionBarDrawerToggle;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
FragmentTransaction tx = getSupportFragmentManager().beginTransaction();
tx.replace(R.id.flContent, new HomeFragment());
tx.commit();
toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
//drawer layout
drawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
actionBarDrawerToggle= setupDrawerToggle();
drawerLayout.setDrawerListener(actionBarDrawerToggle);
//navigation view
navigationView= (NavigationView) findViewById(R.id.nvView);
// Setup drawer view
setupDrawerContent(navigationView);
actionBarDrawerToggle.syncState();
// default item of navigation view
// navigationView.getMenu().getItem(0).setChecked(true);
navigationView.setCheckedItem(R.id.nav_item_home);
}//onCreate
private ActionBarDrawerToggle setupDrawerToggle() {
return new ActionBarDrawerToggle(this, drawerLayout, toolbar, R.string.drawer_open, R.string.drawer_close);
}
private void setupDrawerContent(NavigationView navigationView) {
navigationView.setNavigationItemSelectedListener(
new NavigationView.OnNavigationItemSelectedListener() {
#Override
public boolean onNavigationItemSelected(MenuItem menuItem) {
selectDrawerItem(menuItem);
return true;
}
});
}
public void selectDrawerItem(MenuItem menuItem) {
if (menuItem.getItemId()==R.id.nav_item_setting){
startActivityForResult(new Intent(this, SettingActivity.class), 1002);
}
if (menuItem.getItemId()== R.id.nav_item_help) {
//startActivityForResult(new Intent(this,HelpActivity.class),1000);
startActivity(new Intent(MainActivity.this,HelpActivity.class));
}
// Create a new fragment and specify the fragment to show based on nav item clicked
android.support.v4.app.Fragment fragment = null /*new android.support.v4.app.Fragment()*/;
Class fragmentClass = null;
switch(menuItem.getItemId()) {
case R.id.nav_item_home:
fragmentClass = HomeFragment.class;
break;
case R.id.nav_item_knowledge:
fragmentClass = HomeFragment.class;
break;
/* case R.id.nav_item_help:
fragmentClass = HelpActivity.class;
break;*/
case R.id.nav_item_about:
fragmentClass =AboutFragment.class;
break;
default:
fragmentClass = HomeFragment.class;
break;
} try {
fragment = (android.support.v4.app.Fragment) fragmentClass.newInstance();
} catch (Exception e) {
e.printStackTrace();
}
// Insert the fragment by replacing any existing fragment
android.support.v4.app.FragmentManager fragmentManager = getSupportFragmentManager();
android.support.v4.app.Fragment currentFragment = getSupportFragmentManager().findFragmentById(R.id.flContent);
if(currentFragment==null){
fragmentManager.beginTransaction().add(R.id.flContent, fragment).commit();
}else{
fragmentManager.beginTransaction().replace(R.id.flContent, fragment).commit();
}
// Highlight the selected item has been done by NavigationView
menuItem.setChecked(true);
// Set action bar title
setTitle(menuItem.getTitle());
// Close the navigation drawer
drawerLayout.closeDrawers();
}
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
// Pass any configuration change to the drawer toggles
actionBarDrawerToggle.onConfigurationChanged(newConfig);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
if (actionBarDrawerToggle.onOptionsItemSelected(item)) {
return true;
} return super.onOptionsItemSelected(item);
}
#Override
protected void onPostCreate(Bundle savedInstanceState) {
super.onPostCreate(savedInstanceState); // `onPostCreate` called when activity start-up is complete after `onStart()`
}
#Override
public void onBackPressed() {
MainActivity.this.finish();
}
}
in your xml:
<android.support.design.widget.NavigationView
android:id="#+id/navigation_view"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:layout_gravity="right"
android:background="#drawable/background_drawer"
app:headerLayout="#layout/nav_header"
app:itemIconTint="#color/colorPrimary"
app:menu="#menu/menu_navigation" />
you have to add help options in your menu_navigation
<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android">
<group android:checkableBehavior="single">
<item
android:id="#+id/nav_item_help"
android:icon="#drawable/profile_icon"
android:title="Help" />
</group>
</menu>
Also in your MainActivity:
public void selectDrawerItem(MenuItem menuItem) {
// Create a new fragment and specify the fragment to show based on nav item clicked
android.support.v4.app.Fragment fragment = null /*new android.support.v4.app.Fragment()*/;
Class fragmentClass = null;
switch(menuItem.getItemId()) {
case R.id.nav_item_setting:
Intent i = new Intent(MainActivity.this, SettingActivity.class);
startActivity(i);
break;
case R.id.nav_item_help:
Intent i = new Intent(MainActivity.this, HelpActivity.class);
startActivity(i);
break;
case R.id.nav_item_home:
fragmentClass = HomeFragment.class;
break;
case R.id.nav_item_knowledge:
fragmentClass = HomeFragment.class;
break;
/* case R.id.nav_item_help:
fragmentClass = HelpActivity.class;
break;*/
case R.id.nav_item_about:
fragmentClass =AboutFragment.class;
break;
default:
fragmentClass = HomeFragment.class;
break;
} try {
fragment = (android.support.v4.app.Fragment) fragmentClass.newInstance();
} catch (Exception e) {
e.printStackTrace();
}
// Insert the fragment by replacing any existing fragment
android.support.v4.app.FragmentManager fragmentManager = getSupportFragmentManager();
android.support.v4.app.Fragment currentFragment = getSupportFragmentManager().findFragmentById(R.id.flContent);
if(currentFragment==null){
fragmentManager.beginTransaction().add(R.id.flContent, fragment).commit();
}else{
fragmentManager.beginTransaction().replace(R.id.flContent, fragment).commit();
}
// Highlight the selected item has been done by NavigationView
menuItem.setChecked(true);
// Set action bar title
setTitle(menuItem.getTitle());
// Close the navigation drawer
drawerLayout.closeDrawers();
}
In your preference manager:
public void setFirstTimeLaunch(boolean isFirstTime) {
Editor editor = pref.edit();
editor.putBoolean(IS_FIRST_TIME_LAUNCH, isFirstTime);
editor.commit();
}
difference between startactivity and startActivityForResult is:
1. startActvity():
startActivity() will start the activity you want to start without worrying about getting any result from new child activity started by startActivity to parent activity.
2. startAcitvityForResult():
startAcitvityForResult() starts another activity from your activity and it expect to get some data from newly started child activity by startAcitvityForResult() and return that to parent activity.
see this blog:https://malikshafique.wordpress.com/2012/06/14/android-startactivity-and-startactivityforresult/
in my navigation drawer there are 5 menu items.one of them is about us item.when I click on this item, I call AboutUsFragment and show it(its content is just a text).but when I click onBackPress, fragment is gone but its texts remains on my activity.how can I solve this problem?what`s it related to?!
select item of navigation drawer in my activity:
public void selectItem(int position) {
Fragment fragment = null;
switch (position) {
case 0:
if (!Constants.login_state) {
fragment = new LoginFragment();
} else {
Logout();
}
break;
case 1:
Constants.filter = false;
Constants.gender = "-1";
fragment = new HomeFragment();
break;
case 2:
Constants.filter = false;
Constants.gender = "2";
StyleFragment.SortingMode = 1;
fragment = new StyleFragment();
break;
case 3:
Constants.filter = false;
Constants.gender = "1";
StyleFragment.SortingMode = 1;
fragment = new StyleFragment();
break;
case 4:
fragment = new AboutUsFragment();
break;
default:
break;
}
if (fragment != null) {
FragmentTransaction fragmentManager = getSupportFragmentManager().beginTransaction();
fragmentManager.replace(R.id.rl_container, fragment);
fragmentManager.addToBackStack(null);
fragmentManager.commit();
mDrawerList.setItemChecked(position, true);
mDrawerList.setSelection(position);
setTitle(mNavigationDrawerItemTitles[position]);
mDrawerLayout.closeDrawer(Gravity.END);
} else {
Log.e("HomeActivity", "Error in creating fragment");
}
}
and AboutUsFragment:
public class AboutUsFragment extends android.support.v4.app.Fragment{
private View view;
private TextView about_us_fragment_text_view;
public static AboutUsFragment newInstance() {
AboutUsFragment fragment = new AboutUsFragment();
Bundle args = new Bundle();
fragment.setArguments(args);
return fragment;
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
view=inflater.inflate(R.layout.fragment_about_us, container, false);
Casting(view);
about_us_fragment_text_view.setText(getResources().getString(R.string.about_us));
ChangeUIFont.ChangeFont((ViewGroup) view, getContext());
return view;
}
//casting parameters
public void Casting(View v){
about_us_fragment_text_view= (TextView) v.findViewById(R.id.about_us_fragment_text_view);
}}
onBackPress in my activity:
#Override
public void onBackPressed() {
if (SearchOpened) {
lv_searchResult.setVisibility(View.GONE);
SearchOpened = false;
} else
super.onBackPressed();
}
---------------------------------------AfterSearching-------------------------------------------
Finally I found the solution!
in my fragment I added below code:
public static final String FRAGMENT_NAME = AboutUsFragment.class.getName();
and in my activity,I set the tag of fragment when I call it,instead of null!
fragmentManager.replace(R.id.rl_container, fragment,fragmentName);
used this method instead of onBackPressed
if you have toolbar then here is my solution,
type under the oncreate method below toolbar,
assert getSupportActionBar() != null;
// getSupportActionBar().setHomeButtonEnabled(true);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
}
and set this code in your manifest file for your fragment
<activity android:name=".yourCurrentFragment">
<meta-data
android:name="android.support.PARENT_ACTIVITY"
android:value=".whichActivityYouWantToGo" />
</activity>
Try this:
#Override
public void onBackPressed() {
if (getFragmentManager().getBackStackEntryCount() == 0) {
super.onBackPressed();
} else {
getFragmentManager().popBackStack();
}
I've been searching and thinking how to implement the desire behaviour that I want when switching back and forth between fragments when using a Navigation Drawer. Actually the documentation says:
When using fragments in your app, individual FragmentTransaction objects may represent context changes that should be added to the back stack. For example, if you are implementing a master/detail flow on a handset by swapping out fragments, you should ensure that pressing the Back button on a detail screen returns the user to the master screen
So in my app I have a MainActivity that controls everything and a navigation layout within you can change between predefined options. This is the view when you launch the app
When you click on an item in the navigation drawer it opens a new fragment that replaces the main_content as follows:
At this point the behaviour is the correct one, so if you want to change the options you need to open the navigation drawer again to toggle between the menu options.
This is the Main Activity (notice that there is no Drawer Toggle)
MainActivity.java
public class MainActivity extends AppCompatActivity {
ActionBarDrawerToggle mDrawerToggle;
private DrawerLayout drawerLayout;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mSnackBarView = findViewById(R.id.myCoordinatorLayout);
setToolbar(); // Set Toolbar como action bar
if (savedInstanceState != null) {
mCurrentSelectedPosition = savedInstanceState.getInt(STATE_SELECTED_POSITION);
mFromSavedInstanceState = true;
}
drawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
if (navigationView != null) {
setupDrawerContent(navigationView);
}
drawerTitle = getResources().getString(R.string.app_name);
if (savedInstanceState == null) {
selectItem(drawerTitle, mCurrentSelectedPosition);
}
}
private void setToolbar() {
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
final ActionBar ab = getSupportActionBar();
if (ab != null) {
// Poner ícono del drawer toggle
ab.setHomeAsUpIndicator(R.drawable.ic_menu);
ab.setDisplayHomeAsUpEnabled(true);
}
}
private void setupDrawerContent(final NavigationView navigationView) {
navigationView.setNavigationItemSelectedListener(
new NavigationView.OnNavigationItemSelectedListener() {
#Override
public boolean onNavigationItemSelected(MenuItem menuItem) {
// Marcar item presionado
menuItem.setChecked(true);
// Crear nuevo fragmento
String title = menuItem.getTitle().toString();
int id = menuItem.getItemId();
selectItem(title, id);
return true;
}
}
);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
if (!drawerLayout.isDrawerOpen(GravityCompat.START)) {
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
return super.onCreateOptionsMenu(menu);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home:
drawerLayout.openDrawer(GravityCompat.START);
return true;
}
return super.onOptionsItemSelected(item);
}
private void selectItem(String title, int id) {
Bundle args = new Bundle();
args.putString(PlaceholderFragment.ARG_SECTION_TITLE, title);
Fragment fragment = PlaceholderFragment.newInstance(title);
fragment.setArguments(args);
FragmentManager fragmentManager = getSupportFragmentManager();
fragmentManager
.beginTransaction()
.replace(R.id.main_content, fragment)
.commit();
switch (id) {
case R.id.nav_localizacion:
//Snackbar.make(mSnackBarView, R.string.menu_localization, Snackbar.LENGTH_SHORT).show();
mCurrentSelectedPosition = 0;
LocalizacionFragment fragment_localizacion = new LocalizacionFragment();
// fragmentManager = getSupportFragmentManager();
Snackbar.make(mSnackBarView, R.string.menu_localization, Snackbar.LENGTH_SHORT).show();
fragmentManager
.beginTransaction()
.replace(R.id.main_content, fragment_localizacion)
.commit();
break;
case R.id.nav_productos:
Snackbar.make(mSnackBarView, R.string.menu_productos, Snackbar.LENGTH_SHORT).show();
mCurrentSelectedPosition = 1;
fragmentManager
.beginTransaction()
.replace(R.id.main_content, fragment)
.commit();
break;
case R.id.nav_consejos:
Snackbar.make(mSnackBarView, R.string.menu_consejos, Snackbar.LENGTH_SHORT).show();
mCurrentSelectedPosition = 3;
ConsejosFragment fragment_consejo = new ConsejosFragment();
fragmentManager
.beginTransaction()
.replace(R.id.main_content, fragment_consejo)
.commit();
break;
default:
break;
}
drawerLayout.closeDrawers(); // Cerrar drawer
setTitle(title); // título actual
}
}
I don't use the hamburger icon because it hides under the Navigation Layout, but here is the thing. When you click on "Recetas" in the recycle view it open a new fragment (replace) but now I want to show the up caret icon and give proper back navigation to my app.
Here is the code of the "Consejos" fragment class
Consejos.java
public class ConsejosFragment extends Fragment {
RecyclerView mRecycler;
ConsejosAdapter mAdapter;
FragmentActivity mActivity;
#Override
public void onAttach(Activity activity) {
super.onAttach(activity);
this.mActivity = (FragmentActivity) activity;
setRetainInstance(true);
}
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
setHasOptionsMenu(true);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
List items = new ArrayList();
items.add(new ConsejosInfo("Recetas", R.drawable.icon_recetas));
/* Inflamos el layout */
View v = inflater.inflate(R.layout.consejos_layout_recycler, container, false);
/* Obtenemos el Recycle */
mRecycler = (RecyclerView) v.findViewById(R.id.recycler_consejos);
/* Creamos el adaptador */
mAdapter = new ConsejosAdapter(mActivity, items);
/* Set click en adapter */
return v;
}
#Override
public void onViewCreated(View view, Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
mRecycler.setHasFixedSize(true);
mRecycler.setLayoutManager(new LinearLayoutManager(getActivity()));
mRecycler.setAdapter(mAdapter);
}
}
And this is the adapter that the Recyclerview use and handles the click on the item inside:
Adapter.java
public class ConsejosAdapter extends RecyclerView.Adapter<ConsejosAdapter.ConsejosViewHolder> {
private List<ConsejosInfo> _items = new ArrayList<ConsejosInfo>();
private final FragmentActivity mActivity;
private Context context;
public ConsejosAdapter(FragmentActivity mActivity, List<ConsejosInfo> items) {
this._items = items;
this.mActivity = mActivity;
}
#Override
public int getItemCount() {
return _items.size();
}
#Override
public ConsejosViewHolder onCreateViewHolder(ViewGroup viewGroup, int viewType) {
View v = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.cardview_consejos, viewGroup, false);
return new ConsejosViewHolder(v);
}
#Override
public void onBindViewHolder(ConsejosViewHolder viewHolder, int position) {
viewHolder.imagen.setImageResource(_items.get(position).get_imagen());
viewHolder.nombre.setText(_items.get(position).get_nombre());
}
public class ConsejosViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener {
public ImageView imagen;
public TextView nombre;
public ConsejosViewHolder(final View itemView) {
super(itemView);
imagen = (ImageView) itemView.findViewById(R.id.consejos_imagen);
nombre = (TextView) itemView.findViewById(R.id.consejos_nombre);
itemView.setOnClickListener(this);
}
#Override
public void onClick(View v) {
RecetasFragment recetasFragment = new RecetasFragment();
FragmentManager fragmentManager = mActivity.getSupportFragmentManager();
fragmentManager
.beginTransaction()
.replace(R.id.main_content, recetasFragment)
.addToBackStack(null)
.commit();
}
}
}
In the Consejos Adapter I added to backstack the fragment before calling the new fragment (inside fragment) and that changes the behaviour of the back button, so before this if you press the back button is closes the app but now it takes you to the Consejos fragment, but now I want to add the up caret and make the exactly same operation as when you click the back button but I don't know how to achieve it.
Please feel free to ask for more code
Thank you very much
I will give you the full answer:
We will use the interfaces to communicate with the MainActivity from RecetasFragment so we can enable and disable navigation back button.
RecetasFragment class:
import android.app.Activity;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
/**
* Created by hema on 8/19/2015.
*/
public class RecetasFragment extends Fragment {
private CommunicateWithActivity mWithActivity;
public RecetasFragment() {
}
#Override
public void onAttach(Activity activity) {
super.onAttach(activity);
try {
mWithActivity = (CommunicateWithActivity) activity; // MainActivity must implement CommunicateWithActivity interface.
mWithActivity.enableNavigationBack(true); // We enable navigation back here.
} catch (ClassCastException e) {
throw new ClassCastException(activity.toString()
+ " must implement CommunicateWithActivity");
}
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
return inflater.inflate(R.layout.fragment_recetas, container, false);
}
#Override
public void onDestroy() {
super.onDestroy();
mWithActivity.enableNavigationBack(false); // We disable navigation back here, restore menu icon.
}
public interface CommunicateWithActivity {
void enableNavigationBack(boolean enable);// we will implement this method in MainActivity class.
}
}
And in MainActivity class we will implement CommunicateWithActivity interface, Modify your MainActivity class (only required modifications):
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.Toolbar;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
public class MainActivity extends AppCompatActivity implements RecetasFragment.CommunicateWithActivity {
private Toolbar mToolbar;
private DrawerLayout drawerLayout;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mToolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(mToolbar);
mToolbar.setNavigationIcon(R.drawable.ic_menu);
mSnackBarView = findViewById(R.id.myCoordinatorLayout);
if (savedInstanceState != null) {
mCurrentSelectedPosition = savedInstanceState.getInt(STATE_SELECTED_POSITION);
mFromSavedInstanceState = true;
}
drawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
if (navigationView != null) {
setupDrawerContent(navigationView);
}
drawerTitle = getResources().getString(R.string.app_name);
if (savedInstanceState == null) {
selectItem(drawerTitle, mCurrentSelectedPosition);
}
}
private void setupDrawerContent(final NavigationView navigationView) {
navigationView.setNavigationItemSelectedListener(
new NavigationView.OnNavigationItemSelectedListener() {
#Override
public boolean onNavigationItemSelected(MenuItem menuItem) {
// Marcar item presionado
menuItem.setChecked(true);
// Crear nuevo fragmento
String title = menuItem.getTitle().toString();
int id = menuItem.getItemId();
selectItem(title, id);
return true;
}
}
);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
if (!drawerLayout.isDrawerOpen(GravityCompat.START)) {
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
return super.onCreateOptionsMenu(menu);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home:
drawerLayout.openDrawer(GravityCompat.START);
return true;
}
return super.onOptionsItemSelected(item);
}
private void selectItem(String title, int id) {
Bundle args = new Bundle();
args.putString(PlaceholderFragment.ARG_SECTION_TITLE, title);
Fragment fragment = PlaceholderFragment.newInstance(title);
fragment.setArguments(args);
FragmentManager fragmentManager = getSupportFragmentManager();
fragmentManager
.beginTransaction()
.replace(R.id.main_content, fragment)
.commit();
switch (id) {
case R.id.nav_localizacion:
//Snackbar.make(mSnackBarView, R.string.menu_localization, Snackbar.LENGTH_SHORT).show();
mCurrentSelectedPosition = 0;
LocalizacionFragment fragment_localizacion = new LocalizacionFragment();
// fragmentManager = getSupportFragmentManager();
Snackbar.make(mSnackBarView, R.string.menu_localization, Snackbar.LENGTH_SHORT).show();
fragmentManager
.beginTransaction()
.replace(R.id.main_content, fragment_localizacion)
.commit();
break;
case R.id.nav_productos:
Snackbar.make(mSnackBarView, R.string.menu_productos, Snackbar.LENGTH_SHORT).show();
mCurrentSelectedPosition = 1;
fragmentManager
.beginTransaction()
.replace(R.id.main_content, fragment)
.commit();
break;
case R.id.nav_consejos:
Snackbar.make(mSnackBarView, R.string.menu_consejos, Snackbar.LENGTH_SHORT).show();
mCurrentSelectedPosition = 3;
ConsejosFragment fragment_consejo = new ConsejosFragment();
fragmentManager
.beginTransaction()
.replace(R.id.main_content, fragment_consejo)
.commit();
break;
default:
break;
}
drawerLayout.closeDrawers(); // Cerrar drawer
setTitle(title); // título actual
}
#Override
public void enableNavigationBack(boolean enable) {
if(enable) {
// We enable the navigation back button here
mToolbar.setNavigationIcon(R.drawable.abc_ic_ab_back_mtrl_am_alpha);
mToolbar.setNavigationOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// On navigation back button clicked.
if(getSupportFragmentManager().getBackStackEntryCount() > 0) { // Check if there is fragments in BackStack.
getSupportFragmentManager().popBackStack(); // PopBackStack.
} else {
// You can implement this part as you want.
return;
}
}
});
} else {
mToolbar.setNavigationIcon(R.drawable.ic_menu);
mToolbar.setNavigationOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if(drawerLayout != null) {
drawerLayout.openDrawer(Gravity.LEFT);
}
}
});
}
}
}
Please let me know if there is something you don't understand.
I have a Navigation Drawer (so I use Fragments):
MainActivity (FragmentActivity)
Fragment A (Fragment with pictures links for Fragment B, C & D)
Fragment B (Fragment)
Fragment C (Fragment)
Fragment D (Fragment)
My navigation drawer works correctely, but I want to my Fragment A to do links like the menu. Right now, in Fragment A, I call the other Fragments like this:
ImageView contact = (ImageView) getView().findViewById(R.id.secondBlock);
contact.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
Fragment fragment = new ContactezNous();
FragmentManager fragmentManager = getFragmentManager();
FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
fragmentTransaction.replace(R.id.accueil, fragment);
fragmentTransaction.commit();
}
});
But I don't want to use this way, because I have problems finding tags and ids of other Fragments.
I want to know how to change Fragments frome Fragment A by clicking on the link like if I was clicking on the Navigation Drawer links of the Main Activity.
Main Activity:
public class MainActivity extends AppCompatActivity implements FragmentDrawer.FragmentDrawerListener {
private static String TAG = MainActivity.class.getSimpleName();
private Toolbar mToolbar;
private FragmentDrawer drawerFragment;
//Initialisation de l activite avec les donnees necessaires
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mToolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(mToolbar);
getSupportActionBar().setDisplayShowHomeEnabled(true);
drawerFragment = (FragmentDrawer) getSupportFragmentManager().findFragmentById(R.id.fragment_navigation_drawer);
drawerFragment.setUp(R.id.fragment_navigation_drawer, (DrawerLayout) findViewById(R.id.drawer_layout), mToolbar);
drawerFragment.setDrawerListener(this);
// Affichage de la navigation
displayView(0);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
//Ajout des items
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);
}
#Override
public void onDrawerItemSelected(View view, int position) {
displayView(position);
}
private void displayView(int position) {
Fragment fragment = null;
String title = getString(R.string.app_name);
switch (position) {
case 0:
fragment = new Accueil();
title = getString(R.string.title_accueil);
break;
case 1:
fragment = new NosOffres();
title = getString(R.string.title_nosoffres);
break;
case 2:
fragment = new DemandeGratuite();
title = getString(R.string.title_demandegratuite);
break;
case 3:
fragment = new ContactezNous();
title = getString(R.string.title_contact);
break;
case 4:
fragment = new Actualites();
title = getString(R.string.title_actu);
break;
case 5:
fragment = new MentionsLegales();
title = getString(R.string.title_mentions);
break;
default:
break;
}
if (fragment != null) {
FragmentManager fragmentManager = getSupportFragmentManager();
FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
fragmentTransaction.replace(R.id.container_body, fragment);
//fragmentTransaction.addToBackStack("name");
fragmentTransaction.commit();
// libelle du toolbar
TextView titlet;
titlet = (TextView) findViewById(R.id.main_toolbar_title);
titlet.setText(title);
titlet.setTypeface(Typeface.createFromAsset(getAssets(), "fonts/GothamBook.ttf"));
}
}
}
You should use the following common Android fragment pattern:
public class Accueil extends Fragment {
// Your code here...
public interface OnFragmentInteractionListener {
void onInteraction(int id);
}
private OnFragmentInteractionListener mListener;
#Override
public void onAttach(Activity activity) {
super.onAttach(activity);
try {
mListener = (OnFragmentInteractionListener) activity;
} catch (ClassCastException e) {
throw new ClassCastException(activity.toString() + " must implement OnFragmentInteractionListener");
}
}
#Override
public void onDetach() {
super.onDetach();
mListener = null;
}
// ...more code...
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
// ...initialize your View...
ImageView contact = (ImageView) getView().findViewById(R.id.secondBlock);
contact.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// This is how you use the listener
mListener.onInteraction(3);
}
});
// ...more initialization...
}
}
MainActivity.java
public class MainActivity AppCompatActivity
implements FragmentDrawer.FragmentDrawerListener, OnFragmentInteractionListener {
// Your code here...
// Implement OnFragmentInteractionListener
#Override
public void onInteraction(int id) {
// 'id' would be '3' for your 'ContactezNous' fragment
displayView(id);
}
}