Change Fragment from other Fragment like Navigation links - android

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);
}
}

Related

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

how to add Activity class in DrawerLayout in android?

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/

How to pass information to a fragment when an item on a listfragment is clicked

I have a fragment list SecondActivityListFragment that contains a list of items. If an item on the list is clicked, I would like to pass the info of this clicked item to another fragment called ItemViewFragment. I have created an interface class called Communicator but I have no clue how to pass the information through.
SecondActivityListFragment
public class SecondActivityListFragment extends ListFragment {
Communicator communicator;
private ArrayList<SubNote> subNotes;
private SubNoteAdapter subNoteAdapter;
#Override
public void onActivityCreated(Bundle savedInstanceState){
super.onActivityCreated(savedInstanceState);
communicator = (Communicator) getActivity();
subNotes = new ArrayList<SubNote>();
subNotes.add(new SubNote("Product X", "wow", "booo", new BigDecimal(10212).setScale(2, BigDecimal.ROUND_FLOOR), SubNote.Category.HEALTHCARE));
subNotes.add(new SubNote("Product Y", "wow", "booo", new BigDecimal(107866.23).setScale(2, BigDecimal.ROUND_FLOOR), SubNote.Category.DENTAL));
subNotes.add(new SubNote("Product Y", "wow", "booo", new BigDecimal(107866.23).setScale(2, BigDecimal.ROUND_FLOOR), SubNote.Category.DENTAL));
subNotes.add(new SubNote("Product Y", "wow", "booo", new BigDecimal(107866.23).setScale(2, BigDecimal.ROUND_FLOOR), SubNote.Category.DENTAL));
subNotes.add(new SubNote("Product Y", "wow", "booo", new BigDecimal(107866.23).setScale(2, BigDecimal.ROUND_FLOOR), SubNote.Category.DENTAL));
subNotes.add(new SubNote("Product Y", "wow", "booo", new BigDecimal(107866.23).setScale(2, BigDecimal.ROUND_FLOOR), SubNote.Category.DENTAL));
subNotes.add(new SubNote("Product Y", "wow", "booo", new BigDecimal(107866.23).setScale(2, BigDecimal.ROUND_FLOOR), SubNote.Category.DENTAL));
subNotes.add(new SubNote("Product Y", "wow", "booo", new BigDecimal(107866.23).setScale(2, BigDecimal.ROUND_FLOOR), SubNote.Category.DENTAL));
subNoteAdapter = new SubNoteAdapter(getActivity(), subNotes);
setListAdapter(subNoteAdapter);
}
#Override
public void onListItemClick(ListView l, View v, int position, long id){
super.onListItemClick(l, v, position, id);
launchNoteDetailActivity(position);
}
#Override
public void onAttach(Context context) {
super.onAttach(context);
if (context instanceof Communicator) {
communicator = (Communicator) context;
} else {
throw new RuntimeException(context.toString()
+ " must implement Communicator");
}
}
private void launchNoteDetailActivity(int position){
ItemViewFragment itemViewFragment = new ItemViewFragment();
FragmentManager fragmentManager = getFragmentManager();
fragmentManager.beginTransaction().replace(R.id.content_main, itemViewFragment, itemViewFragment.getTag()).commit();
//communicator.respond(position);
// Grab the note information associated with whatever note item we clicked on
//SubNote subNote = (SubNote) getListAdapter().getItem(position);
}
}
MainActivity
public class MainActivity extends AppCompatActivity
implements NavigationView.OnNavigationItemSelectedListener, Communicator {
//public static final String SUB_NOTE_NAME_EXTRA = "com.example.khalid.myapplication2.SubNote Title";
//public static final String SUB_NOTE_BRIEFDESCRIPTION_EXTRA = "com.example.khalid.myapplication2.SubNote BriefDescription";
//public static final String SUB_NOTE_FULLDESCRIPTION_EXTRA = "com.example.khalid.myapplication2.SubNote FullDescription";
//public static final String SUB_NOTE_PRICE_EXTRA = "com.example.khalid.myapplication2.SubNote Price";
//public static final String SUB_NOTE_CATEGORY_EXTRA = "com.example.khalid.myapplication2.SubNote Category";
// ViewPager viewPager;
// CustomSwipeAdapter imgadapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
MainActivityListFragment mainActivityListFragment = new MainActivityListFragment();
FragmentManager fragmentManager = getSupportFragmentManager();
fragmentManager.beginTransaction().replace(R.id.content_main, mainActivityListFragment, mainActivityListFragment.getTag()).commit();
// viewPager = (ViewPager) findViewById(R.id.viewpager1);
// imgadapter = new CustomSwipeAdapter(this);
// viewPager.setAdapter(imgadapter);
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.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.main, menu);
SearchView searchView = (SearchView) menu.findItem(R.id.menu_search).getActionView();
SearchManager searchManager = (SearchManager) getSystemService(SEARCH_SERVICE);
searchView.setSearchableInfo(searchManager.getSearchableInfo(getComponentName()));
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_home) {
MainActivityListFragment mainActivityListFragment = new MainActivityListFragment();
FragmentManager fragmentManager = getSupportFragmentManager();
fragmentManager.beginTransaction().replace(R.id.content_main, mainActivityListFragment, mainActivityListFragment.getTag()).commit();
setTitle("ThimarAljazirah");
} else if (id == R.id.nav_notification) {
NotificationsFragment notificationsFragment = new NotificationsFragment();
FragmentManager fragmentManager = getSupportFragmentManager();
fragmentManager.beginTransaction().replace(R.id.content_main, notificationsFragment, notificationsFragment.getTag()).commit();
setTitle("Notifications");
} else if (id == R.id.nav_messages) {
} else if (id == R.id.nav_categories) {
} else if (id == R.id.nav_deals) {
} else if (id == R.id.nav_settings) {
SettingFragment settingFragment = new SettingFragment();
FragmentManager fragmentManager = getSupportFragmentManager();
fragmentManager.beginTransaction().replace(R.id.content_main, settingFragment, settingFragment.getTag()).commit();
setTitle("Settings");
} else if (id == R.id.nav_help_contact) {
} else if (id == R.id.nav_profile) {
MyProfile myProfile = new MyProfile();
FragmentManager fragmentManager = getSupportFragmentManager();
fragmentManager.beginTransaction().replace(R.id.content_main, myProfile, myProfile.getTag()).commit();
setTitle("My Profile");
} else if (id == R.id.nav_signout) {
SingOutFragment singOutFragment = SingOutFragment.newInstance("1", "2");
FragmentManager fragmentManager = getSupportFragmentManager();
fragmentManager.beginTransaction().replace(R.id.content_main,singOutFragment, singOutFragment.getTag()).commit();
} else if (id == R.id.nav_about_us) {
AboutUsFragment aboutUsFragment = new AboutUsFragment();
FragmentManager fragmentManager = getSupportFragmentManager();
fragmentManager.beginTransaction().replace(R.id.content_main,aboutUsFragment, aboutUsFragment.getTag()).commit();
setTitle("About Thimar Aljazirah");
}
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
drawer.closeDrawer(GravityCompat.START);
return true;
}
#Override
public void respond(int position) {
ItemViewFragment itemViewFragment = new ItemViewFragment();
}
}
ItemViewFragment
public class ItemViewFragment extends Fragment {
public ItemViewFragment() {
// Required empty public constructor
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
return inflater.inflate(R.layout.fragment_item_view, container, false);
}
}
Communicator
public interface Communicator {
public void respond (int position);
}
If both fragments are in the same Activity, this activity can implement a listener(interface) that listens for a click from fragment A and transfers data to the fragment B.
public interface Communicator{
void onResponse(YourData data);
}
public class MainActivity extends AppCompatActivity implements Communicator {
#Override
public void onResponse(Your data) {
// add data to other fragment
}
}
In order to pass the data to the activity, you have to get the listener from inside of the fragment.
YourFragment extends Fragment {
private Communicator communicator;
#Override
public void onAttach(Context context) {
super.onAttach(context);
Object host = getHost();
if (host instanceof Communicator) {
communicator= (Communicator) host;
}
}
#Override
public void onDetach() {
super.onDetach();
communicator= null;
}
}
Then when onClick happens for the list view. You have to do.
onClick {
communicator.onResponse(//your data here);
}
In the other fragment B you have to create a newInstance(//Your data) method like this.
public static YourFragment newInstance(String string) {
Bundle args = new Bundle();
args.putString(STRING_KEY, string);
YourFragment fragment = new YourFragment ();
fragment.setArguments(args);
return fragment;
}
and then onCreate you can retrieve the data given to the fragment
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
String string = getArguments().getString(STRING_KEY);
}
you shouldn't use the default constructor to instantiate the fragment because of the way Android recreates fragments and activities. That's why we create newInstance method.
Communicating with Other Fragments of activity
1>.Define an Interface
public class HeadlinesFragment extends ListFragment {
OnHeadlineSelectedListener mCallback;
// Container Activity must implement this interface
public interface OnHeadlineSelectedListener {
public void onArticleSelected(int position);
}
#Override
public void onAttach(Activity activity) {
super.onAttach(activity);
// This makes sure that the container activity has implemented
// the callback interface. If not, it throws an exception
try {
mCallback = (OnHeadlineSelectedListener) activity;
} catch (ClassCastException e) {
throw new ClassCastException(activity.toString()
+ " must implement OnHeadlineSelectedListener");
}
}
...
}
2>.implement the interface into Activity.
public static class MainActivity extends Activity
implements HeadlinesFragment.OnHeadlineSelectedListener{
...
public void onArticleSelected(int position) {
// The user selected the headline of an article from the HeadlinesFragment
// Do something here to display that article
}
}
3>.The host activity can deliver messages to a fragment by capturing the Fragment instance with findFragmentById(), then directly call the fragment's public methods

NavigationDrawer not show the view

I have a Navigation Drawer with Navigation View, there are four tabs, one of them is a fragment, which includes ViewPager, ie is a host for the other fragments. Everything works fine, but when switched from fragment with ViewPager any other fragment of NavigationDrawer shows nothing. Checked logs, onCreate, onCreateView these fragments are called, but why does not display... Who knows why?
NavigationDrawer
public class NavigationDrawerHost extends AppCompatActivity implements
NavigationView.OnNavigationItemSelectedListener {
//буду использовать эту активность как хост под все фрагменты, чтобы верно работал мой drawer!
public static String WHERE_FROM = NavigationDrawerHost.class.getSimpleName();
public static Toolbar toolbar;
public static ProgressBar progressBar;
private DrawerLayout drawer;
private NavigationView navigationView;
private ActionBarDrawerToggle drawerToggle;
private int navItemId;
private static final String NAV_ITEM_ID = "NAV_ITEM_ID";
private TextView userFirstNameTextView, userLastNameTextView;
private ImageView userPhotoImageView;
private VKAccessToken access_token; //токен это информация о правах доступа
private VKApiUser user; //текущий пользователь
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.navigation_drawer_host);
progressBar = (ProgressBar) findViewById(R.id.progressBar);
drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
// Find the toolbar view inside the activity layout
toolbar = (Toolbar) findViewById(R.id.toolbar);
// Set a Toolbar to replace the ActionBar.
setSupportActionBar(toolbar);
//setTitle(R.string.drawer_menu_posts);
// load saved navigation state if present
if (null == savedInstanceState) {
navItemId = R.id.posts_fragment;
} else {
navItemId = savedInstanceState.getInt(NAV_ITEM_ID);
}
// Find our drawer view
navigationView = (NavigationView) findViewById(R.id.nvView);
navigationView.setNavigationItemSelectedListener(this);
// select the correct nav menu item
navigationView.getMenu().findItem(navItemId).setChecked(true);
// если хотим добавить какие-то элементы в наш header,
// то нужно добавить их в layout, а затем инициализировать нижеприведенным способом
// Inflate the header view at runtime
View headerLayout = navigationView.inflateHeaderView(R.layout.nav_header);
// We can now look up items within the header if needed
userFirstNameTextView = (TextView) headerLayout.findViewById(R.id.user_first_name);
userLastNameTextView = (TextView) headerLayout.findViewById(R.id.user_last_name);
userPhotoImageView = (ImageView) headerLayout.findViewById(R.id.user_photo);
drawerToggle = new ActionBarDrawerToggle(this, drawer, toolbar, R.string.drawer_open, R.string.drawer_close);
// Tie DrawerLayout events to the ActionBarToggle
drawer.setDrawerListener(drawerToggle);
drawerToggle.syncState();
selectItem(navItemId);
}
#Override
protected void onSaveInstanceState(final Bundle outState) {
super.onSaveInstanceState(outState);
outState.putInt(NAV_ITEM_ID, navItemId);
}
// Menu icons are inflated just as they were with actionbar
#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) {
switch (item.getItemId()) {
case R.id.menu_exit:
//quitDialog();
VKSdk.logout();
finish();
return true;
default:
return drawerToggle.onOptionsItemSelected(item) || super.onOptionsItemSelected(item);
}
}
// Make sure this is the method with just `Bundle` as the signature
#Override
protected void onPostCreate(Bundle savedInstanceState) {
super.onPostCreate(savedInstanceState);
drawerToggle.syncState();
}
#Override
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
// Pass any configuration change to the drawer toggles
drawerToggle.onConfigurationChanged(newConfig);
}
private void selectItem(final int itemId) {
// perform the actual navigation logic, updating the main content fragment etc
// Create a new fragment and specify the planet to show based on position
Fragment fragment = null;
Class fragmentClass = null;
switch (itemId) {
case R.id.posts_fragment:
fragmentClass = PostsFragment.class;
fragment = new PostsFragment();
break;
case R.id.albums_fragment:
fragmentClass = FragmentTest.class;
fragment = new FragmentTest();
break;
case R.id.friends_fragment:
fragmentClass = FragmentTest.class;
fragment = new FragmentTest();
break;
case R.id.likes_fragment:
fragmentClass = LikesFragment.class;
fragment = new LikesFragment();
break;
/*default:
fragmentClass = PostsFragment.class;*/
}
/*try {
fragment = (Fragment) fragmentClass.newInstance();
} catch (Exception e) {
e.printStackTrace();
}*/
// Insert the fragment by replacing any existing fragment
FragmentManager fragmentManager = getSupportFragmentManager();
FragmentTransaction transaction = fragmentManager.beginTransaction();
transaction.replace(R.id.fragment_container, fragment);
transaction.addToBackStack(null);
transaction.commit();
drawer.closeDrawers();
}
#Override
public boolean onNavigationItemSelected(final MenuItem item) {
// update highlighted item in the navigation menu
item.setChecked(true);
setTitle(item.getTitle());
navItemId = item.getItemId();
// allow some time after closing the drawer before performing real navigation
// so the user can see what is happening
drawer.closeDrawer(GravityCompat.START);
selectItem(item.getItemId());
return true;
}
#Override
public void onBackPressed() {
if (drawer.isDrawerOpen(GravityCompat.START)) {
drawer.closeDrawer(GravityCompat.START);
} else if (getSupportFragmentManager().getBackStackEntryCount() == 0) {
quitDialog();
} else {
getSupportFragmentManager().popBackStack();
}
}
private void quitDialog() {
AlertDialog.Builder quitDialog = new AlertDialog.Builder(this);
quitDialog.setTitle("Вы хотите выйти?");
quitDialog.setPositiveButton("Да", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
//стираем БД
Delete.tables(PostTable.class, PictureTable.class, PostTableMyLikes.class, PictureTableMyLikes.class);
FlowManager.getDatabase(WallDatabase.DB_NAME).reset(NavigationDrawerHost.this);
FlowManager.getDatabase(WallDatabaseMyLikes.DB_NAME).reset(NavigationDrawerHost.this);
Intent intent = new Intent(Intent.ACTION_MAIN);
intent.addCategory(Intent.CATEGORY_HOME);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(intent);
}
});
quitDialog.setNegativeButton("Нет",
new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
// TODO Auto-generated method stub
}
});
quitDialog.show();
}
}
ViewPager host for fragments, which needs to display through ViewPager
//этот фрагмент является хостом для MyLikesFragment и FriendLikesFragment, так же тут содержатся табы
public class LikesFragment extends Fragment {
public static String WHERE_FROM_FRIENDS_LIKES = LikesFragment.class.getSimpleName() + "_FRIENDSLIKES";
private ViewPager viewPager;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.likes_fragment, container, false);
TabLayout tabLayout = (TabLayout) v.findViewById(R.id.tab_layout);
tabLayout.addTab(tabLayout.newTab().setText("Мои лайки"));
tabLayout.addTab(tabLayout.newTab().setText("Лайки друзей"));
tabLayout.setTabGravity(TabLayout.GRAVITY_FILL);
viewPager = (ViewPager) v.findViewById(R.id.view_pager);
viewPager.addOnPageChangeListener(new TabLayout.TabLayoutOnPageChangeListener(tabLayout));
viewPager.setAdapter(new LikesPagerAdapter(getChildFragmentManager()));
tabLayout.setOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
#Override
public void onTabSelected(TabLayout.Tab tab) {
viewPager.setCurrentItem(tab.getPosition());
}
#Override
public void onTabUnselected(TabLayout.Tab tab) {
}
#Override
public void onTabReselected(TabLayout.Tab tab) {
}
});
return v;
}
public static class LikesPagerAdapter extends FragmentPagerAdapter {
public LikesPagerAdapter(FragmentManager fm) {
super(fm);
}
#Override
public int getCount() {
return 2;
}
//сделано так, чтобы передавать те аргументы, от которых будет зависеть функционал фрагмента
#Override
public Fragment getItem(int position) {
return (position == 0) ? new MyLikesPostsFragment() : new PostsFragment();
}
#Override
public CharSequence getPageTitle(int position) {
return (position == 0) ? "Мои лайки" : "Лайки друзей";
}
}
}
P.S. And after going to the same fragment ViewPager select several items in drawer, this should not be
The problem was that I called adapter.notifyDataSetChanged() in the main thread and onPostExecute() in AsyncTask. My carelessness...

Implement back navigation with DrawerLayout and AppCompatActivity without DrawerToggle

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.

Categories

Resources