How to open navigationview selected item - android

I am following this tutorial,i made some changes and i remove tablayout and viewpager,now i am trying to set CheeseListFragment as first item of navigationview but it display nothing,can any one tell me how to achieve that
MainActivity.java
public class MainActivity extends AppCompatActivity {
private DrawerLayout mDrawerLayout;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
final ActionBar ab = getSupportActionBar();
ab.setHomeAsUpIndicator(R.drawable.ic_menu);
ab.setDisplayHomeAsUpEnabled(true);
mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
if (navigationView != null) {
setupDrawerContent(navigationView);
}
// ViewPager viewPager = (ViewPager) findViewById(R.id.viewpager);
/* if (viewPager != null) {
setupViewPager(viewPager);
}*/
FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Snackbar.make(view, "Here's a Snackbar", Snackbar.LENGTH_LONG)
.setAction("Action", null).show();
}
});
// TabLayout tabLayout = (TabLayout) findViewById(R.id.tabs);
// tabLayout.setupWithViewPager(viewPager);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.sample_actions, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home:
mDrawerLayout.openDrawer(GravityCompat.START);
return true;
}
return super.onOptionsItemSelected(item);
}
/* private void setupViewPager(ViewPager viewPager) {
Adapter adapter = new Adapter(getSupportFragmentManager());
adapter.addFragment(new CheeseListFragment(), "Category 1");
adapter.addFragment(new CheeseListFragment(), "Category 2");
adapter.addFragment(new CheeseListFragment(), "Category 3");
viewPager.setAdapter(adapter);
}*/
private void setupDrawerContent(NavigationView navigationView) {
navigationView.setNavigationItemSelectedListener(
new NavigationView.OnNavigationItemSelectedListener() {
#Override
public boolean onNavigationItemSelected(MenuItem menuItem) {
menuItem.setChecked(true);
mDrawerLayout.closeDrawers();
return true;
}
});
}
static class Adapter extends FragmentPagerAdapter {
private final List<Fragment> mFragments = new ArrayList<>();
private final List<String> mFragmentTitles = new ArrayList<>();
public Adapter(FragmentManager fm) {
super(fm);
}
public void addFragment(Fragment fragment, String title) {
mFragments.add(fragment);
mFragmentTitles.add(title);
}
#Override
public Fragment getItem(int position) {
return mFragments.get(position);
}
#Override
public int getCount() {
return mFragments.size();
}
#Override
public CharSequence getPageTitle(int position) {
return mFragmentTitles.get(position);
}
}
}

You need to do following steps.
Replace android.support.design.widget.TabLayout with FrameLayout in layout/include_list_viewpager.xml
<!--<android.support.design.widget.TabLayout-->
<!--android:id="#+id/tabs"-->
<!--android:layout_width="match_parent"-->
<!--android:layout_height="wrap_content" />-->
<FrameLayout
android:id="#+id/container"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#color/window_background">
</FrameLayout>
Add method showCheeseListFragment() to MainActivity class
private void showCheeseListFragment() {
Fragment fragment = new CheeseListFragment();
getSupportFragmentManager().beginTransaction()
.replace(R.id.container, fragment)
.commit();
}
Call this method at end of onCreate in MainActivity.java
// TabLayout tabLayout = (TabLayout) findViewById(R.id.tabs);
// tabLayout.setupWithViewPager(viewPager);
showCheeseListFragment();
Cange NavigationView.OnNavigationItemSelectedListener() to
private void setupDrawerContent(NavigationView navigationView) {
navigationView.setNavigationItemSelectedListener(
new NavigationView.OnNavigationItemSelectedListener() {
#Override
public boolean onNavigationItemSelected(MenuItem menuItem) {
menuItem.setChecked(true);
mDrawerLayout.closeDrawers();
switch (menuItem.getItemId()) {
case R.id.nav_home:
showCheeseListFragment();
return true;
}
return true;
}
}
);
}

Related

Navigation drawer with TabLayout

I am tyring to make a time table . In which Navigation drawer will show days and tab bar will show timing wise lunch, dinner, breakfast.
Question : How to make conditions such that we get to know about both the selected navigation drawer item and selected tab item at same time .
MessActivity.java
public class MainActivity extends AppCompatActivity
implements NavigationView.OnNavigationItemSelectedListener {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_mess);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
TabLayout tablayout = (TabLayout) findViewById(R.id.tabs);
ViewPager viewPager = (ViewPager) findViewById(R.id.viewpager);
tablayout.setupWithViewPager(viewPager);
tabsPager tabsPager = new tabsPager(getSupportFragmentManager());
viewPager.setAdapter(tabsPager);
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);
viewPager.addOnPageChangeListener(new TabLayout.TabLayoutOnPageChangeListener(tablayout));
tablayout.addOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
#Override
public void onTabSelected(TabLayout.Tab tab) {
if (tab.getPosition() == 1) {
toolbar.setBackgroundColor(ContextCompat.getColor(MessActivity.this,
R.color.colorAccent));
tablayout.setBackgroundColor(ContextCompat.getColor(MessActivity.this,
R.color.colorAccent));
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
getWindow().setStatusBarColor(ContextCompat.getColor(MessActivity.this,
R.color.colorAccent));
}
} else if (tab.getPosition() == 2) {
toolbar.setBackgroundColor(ContextCompat.getColor(MessActivity.this,
android.R.color.darker_gray));
tablayout.setBackgroundColor(ContextCompat.getColor(MessActivity.this,
android.R.color.darker_gray));
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
getWindow().setStatusBarColor(ContextCompat.getColor(MessActivity.this,
android.R.color.darker_gray));
}
} else {
toolbar.setBackgroundColor(ContextCompat.getColor(MessActivity.this,
R.color.colorPrimary));
tablayout.setBackgroundColor(ContextCompat.getColor(MessActivity.this,
R.color.colorPrimary));
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
getWindow().setStatusBarColor(ContextCompat.getColor(MessActivity.this,
R.color.colorPrimaryDark));
}
}
}
#Override
public void onTabUnselected(TabLayout.Tab tab) {
}
#Override
public void onTabReselected(TabLayout.Tab tab) {
}
});
}
#Override
public void onBackPressed() {
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
if (drawer.isDrawerOpen(GravityCompat.START)) {
drawer.closeDrawer(GravityCompat.START);
} else {
super.onBackPressed();
}
}
#SuppressWarnings("StatementWithEmptyBody")
#Override
public boolean onNavigationItemSelected(MenuItem item) {
// Handle navigation view item clicks here.
int id = item.getItemId();
if (id == R.id.monday) {
} else if (id == R.id.tuesday) {
} else if (id == R.id.wednesday) {
} else if (id == R.id.thursday) {
} else if (id == R.id.friday) {
} else if (id == R.id.saturday) {
} else if (id == R.id.sunday) {
} else if (id == R.id.next) {
} else if (id == R.id.today) {
}
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
drawer.closeDrawer(GravityCompat.START);
return true;
}
}
tabsPager.java
public class tabsPager extends FragmentStatePagerAdapter {
String[] titles=new String[]{"Breakfast","Lunch","Dinner"};
public tabsPager(FragmentManager fm) {
super(fm);
}
#Nullable
#Override
public CharSequence getPageTitle(int position) {
return titles[position];
}
#Override
public Fragment getItem(int position) {
switch (position) {
case 0:
BreakfastFragment breakfastFragment =new BreakfastFragment();
return breakfastFragment;
case 1: LunchFragment lunchFragment =new LunchFragment();
return lunchFragment;
case 2:
DinnerFragment dinnerFragment =new DinnerFragment();
return dinnerFragment;
}
return null;
}
#Override
public int getCount() {
return 3;
}
}
EDIT
MessActivity
public class MessActivity extends AppCompatActivity
implements NavigationView.OnNavigationItemSelectedListener {
public static int selectedNavigationMenuID= 0;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_mess);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
TabLayout tablayout = (TabLayout) findViewById(R.id.tabs);
ViewPager viewPager = (ViewPager) findViewById(R.id.viewpager);
tablayout.setupWithViewPager(viewPager);
tabsPager tabsPager = new tabsPager(getSupportFragmentManager());
viewPager.setAdapter(tabsPager);
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);
viewPager.addOnPageChangeListener(new TabLayout.TabLayoutOnPageChangeListener(tablayout));
tablayout.addOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
#Override
public void onTabSelected(TabLayout.Tab tab) {
if (tab.getPosition() == 1) {
toolbar.setBackgroundColor(ContextCompat.getColor(MessActivity.this,
R.color.colorAccent));
tablayout.setBackgroundColor(ContextCompat.getColor(MessActivity.this,
R.color.colorAccent));
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
getWindow().setStatusBarColor(ContextCompat.getColor(MessActivity.this,
R.color.colorAccent));
}
} else if (tab.getPosition() == 2) {
toolbar.setBackgroundColor(ContextCompat.getColor(MessActivity.this,
android.R.color.darker_gray));
tablayout.setBackgroundColor(ContextCompat.getColor(MessActivity.this,
android.R.color.darker_gray));
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
getWindow().setStatusBarColor(ContextCompat.getColor(MessActivity.this,
android.R.color.darker_gray));
}
} else {
toolbar.setBackgroundColor(ContextCompat.getColor(MessActivity.this,
R.color.colorPrimary));
tablayout.setBackgroundColor(ContextCompat.getColor(MessActivity.this,
R.color.colorPrimary));
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
getWindow().setStatusBarColor(ContextCompat.getColor(MessActivity.this,
R.color.colorPrimaryDark));
}
}
}
#Override
public void onTabUnselected(TabLayout.Tab tab) {
}
#Override
public void onTabReselected(TabLayout.Tab tab) {
}
});
}
#Override
public void onBackPressed() {
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
if (drawer.isDrawerOpen(GravityCompat.START)) {
drawer.closeDrawer(GravityCompat.START);
} else {
super.onBackPressed();
}
}
#SuppressWarnings("StatementWithEmptyBody")
#Override
public boolean onNavigationItemSelected(MenuItem item) {
// Handle navigation view item clicks here.
selectedNavigationMenuID=item.getItemId();
int id = item.getItemId();
if (id==R.id.next)
{
}
else if(id==R.id.today){}
else if (id == R.id.monday) { }
else if (id == R.id.tuesday) { }
else if (id == R.id.wednesday) {}
else if (id == R.id.thursday) {
} else if (id == R.id.friday) {
} else if (id == R.id.saturday) {
} else if (id == R.id.sunday) {
}
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
drawer.closeDrawer(GravityCompat.START);
return true;
}
}
tabsPager
public tabsPager(FragmentManager fm) {
super(fm);
}
#Nullable
#Override
public CharSequence getPageTitle(int position) {
return titles[position];
}
public void set(int selectedNavigationMenuID) { MessActivity.selectedNavigationMenuID = selectedNavigationMenuID; }
#Override
public Fragment getItem(int position) {
switch (position) {
case 0:set(MessActivity.selectedNavigationMenuID);
BreakfastFragment breakfastFragment=new BreakfastFragment();
return breakfastFragment;
case 1:set(MessActivity.selectedNavigationMenuID);
LunchFragment lunchFragment=new LunchFragment();
return lunchFragment;
case 2:set(MessActivity.selectedNavigationMenuID);
DinnerFragment dinnerFragment=new DinnerFragment();
return dinnerFragment;
}
return null;
}
#Override
public int getCount() {
return 3;
}
}
BreakFastFragment
public class BreakfastFragment extends Fragment {
public BreakfastFragment() {
// Required empty public constructor
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View inf = inflater.inflate(R.layout.fragment_breakfast, container, false);
TextView tv = (TextView) inf.findViewById(R.id.breakfast_textview_id);
if(MessActivity.selectedNavigationMenuID==0)
{
tv.setText("now");}
else if(MessActivity.selectedNavigationMenuID==1)
{
tv.setText("B_today");}
else if(MessActivity.selectedNavigationMenuID==2)
{
tv.setText("B_monday");}
else if(MessActivity.selectedNavigationMenuID==3)
{
tv.setText("B-tuesday");}
else if(MessActivity.selectedNavigationMenuID==4)
{
tv.setText("B-wednesday");}
else if(MessActivity.selectedNavigationMenuID==5)
{
tv.setText("B-thursday");}
else if(MessActivity.selectedNavigationMenuID==6)
{
tv.setText("b-friday");}
else if(MessActivity.selectedNavigationMenuID==7)
{
tv.setText("b-saturday");}
else if(MessActivity.selectedNavigationMenuID==8)
{
tv.setText("b-sunday");}
return inf;
}
}
For Tabs Selected Item it is simple use viewpager.getCurrentItem()
but to get the selected item of navigationview there are two ways
Use a global variable to hold the id
public class MessActivity extends AppCompatActivityimplements NavigationView.OnNavigationItemSelectedListener {
public static int selectedNavigationMenuID= 0; //assuming the first item will be selected by default.
public boolean onNavigationItemSelected(MenuItem item) {
selectedNavigationMenuID=item.getItemId();
}
}
Use a method that will return the selected position from the navigationView
private int getCheckedItem(NavigationView navigationView) {
Menu menu = navigationView.getMenu();
for (int i = 0; i < menu.size(); i++) {
MenuItem item = menu.getIndex(i);
if (item.isChecked()) {
return i;
}
}
return -1;
}
Here comes the new code
Activity
public class MessActivity extends AppCompatActivity implements NavigationView.OnNavigationItemSelectedListener {
private SectionsPagerAdapter mSectionsPagerAdapter;
private ViewPager viewPager;
private Toolbar toolbar;
private TabLayout tablayout;
private DrawerLayout drawer;
private String selectedNavMenu;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_mess);
toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
viewPager = (ViewPager) findViewById(R.id.container);
drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
navigationView.setNavigationItemSelectedListener(this);
selectedNavMenu = "Monday" ;//setting default value
mSectionsPagerAdapter = new SectionsPagerAdapter(getSupportFragmentManager(), selectedNavMenu);
viewPager.setAdapter(mSectionsPagerAdapter);
ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(
this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
drawer.addDrawerListener(toggle);
toggle.syncState();
tablayout = (TabLayout) findViewById(R.id.tabs);
viewPager.addOnPageChangeListener(new TabLayout.TabLayoutOnPageChangeListener(tablayout));
tablayout.addOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
#Override
public void onTabSelected(TabLayout.Tab tab) {
if (tab.getPosition() == 1) {
toolbar.setBackgroundColor(ContextCompat.getColor(MessActivity.this,
R.color.colorAccent));
tablayout.setBackgroundColor(ContextCompat.getColor(MessActivity.this,
R.color.colorAccent));
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
getWindow().setStatusBarColor(ContextCompat.getColor(MessActivity.this,
R.color.colorAccent));
}
} else if (tab.getPosition() == 2) {
toolbar.setBackgroundColor(ContextCompat.getColor(MessActivity.this,
android.R.color.darker_gray));
tablayout.setBackgroundColor(ContextCompat.getColor(MessActivity.this,
android.R.color.darker_gray));
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
getWindow().setStatusBarColor(ContextCompat.getColor(MessActivity.this,
android.R.color.darker_gray));
}
} else {
toolbar.setBackgroundColor(ContextCompat.getColor(MessActivity.this,
R.color.colorPrimary));
tablayout.setBackgroundColor(ContextCompat.getColor(MessActivity.this,
R.color.colorPrimary));
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
getWindow().setStatusBarColor(ContextCompat.getColor(MessActivity.this,
R.color.colorPrimaryDark));
}
}
//Here so that even if ur fragment is regenerated you get the latest value of the selectedNavigationItem
mSectionsPagerAdapter.getItem(viewPager.getCurrentItem()).setSelectedNavigationItem(selectedNavMenu);
}
#Override
public void onTabUnselected(TabLayout.Tab tab) {
}
#Override
public void onTabReselected(TabLayout.Tab tab) {
}
});
}
#Override
public boolean onNavigationItemSelected(#NonNull MenuItem item) {
selectedNavMenu = (String) item.getTitle();
//Just so that new created fragment will get the latest value
mSectionsPagerAdapter.selectedNavigationMenuText = selectedNavMenu;
mSectionsPagerAdapter.getItem(viewPager.getCurrentItem()).setSelectedNavigationItem(selectedNavMenu);
drawer.closeDrawer(GravityCompat.START);
return true;
}
}
PagerAdapter
public class SectionsPagerAdapter extends FragmentPagerAdapter {
SparseArray<PlaceholderFragment> sparseArray = new SparseArray<>();
String selectedNavigationMenuText;
public SectionsPagerAdapter(FragmentManager fm, String selectedNavigationMenuText) {
super(fm);
this.selectedNavigationMenuText = selectedNavigationMenuText;
}
#Override
public PlaceholderFragment getItem(int position) {
try {
if (sparseArray.valueAt(position) != null) {
return sparseArray.get(position);
} else {
PlaceholderFragment placeHolderFragment = PlaceholderFragment.newInstance(position, selectedNavigationMenuText);
sparseArray.put(position, placeHolderFragment);
return placeHolderFragment;
}
} catch (Throwable throwable) {
PlaceholderFragment placeHolderFragment = PlaceholderFragment.newInstance(position, selectedNavigationMenuText);
sparseArray.put(position, placeHolderFragment);
return placeHolderFragment;
}
}
#Override
public int getCount() {
return 3;
}
}
Fragment
public class PlaceholderFragment extends Fragment {
private static final String ARG_SECTION_NUMBER = "section_number";
private static final String SELECTED_NAVIGATION_ITEM = "selectedTab";
private int selecteTabItem;
private TextView textView;
private String selectedMenuItem;
public PlaceholderFragment() {
}
public static PlaceholderFragment newInstance(int sectionNumber, String selectedNavigationItem) {
PlaceholderFragment fragment = new PlaceholderFragment();
Bundle args = new Bundle();
args.putInt(ARG_SECTION_NUMBER, sectionNumber);
args.putString(SELECTED_NAVIGATION_ITEM, selectedNavigationItem);
fragment.setArguments(args);
return fragment;
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_mess, container, false);
textView = rootView.findViewById(R.id.section_label);
selecteTabItem = getArguments().getInt(ARG_SECTION_NUMBER);
selectedMenuItem = getArguments().getString(SELECTED_NAVIGATION_ITEM);
setText();
return rootView;
}
private void setText() {
switch (selecteTabItem) {
case 0:
textView.setText("BREAKFAST : " + selectedMenuItem);
break;
case 1:
textView.setText("LUNCH : " + selectedMenuItem);
break;
case 2:
textView.setText("DINNER : " + selectedMenuItem);
break;
}
}
public void setSelectedNavigationItem(String selectedMenuItem) {
this.selectedMenuItem = selectedMenuItem;
setText();
}
}

Save state of viewpager fragment in navigation drawer fragments

I have Navigation drawer.and in First fragmant of Navigation drawer there is viewpager and there is information coming from network.Viewpager has 2 fragments also.When I switch fragment to Settings fragment of navigation drawer and coming back to this fragment everything is gone..There is no any information..How can i save state of this fragment?Or in which method can i send request to take information from network again
MainActivity
public class MainActivity extends AppCompatActivity implements
NavigationView.OnNavigationItemSelectedListener {
private DrawerLayout drawer;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
navigationView.setNavigationItemSelectedListener(this);
getSupportFragmentManager()
.beginTransaction()
.replace(R.id.motherFragments, FragmentMainPage.newInstance("MainPage"))
.commit();
}
#Override
public void onBackPressed() {
drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
if (drawer.isDrawerOpen(GravityCompat.START)) {
drawer.closeDrawer(GravityCompat.START);
} else {
super.onBackPressed();
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home: {
drawer.openDrawer(GravityCompat.START);
break;
}
}
return super.onOptionsItemSelected(item);
}
#SuppressWarnings("StatementWithEmptyBody")
#Override
public boolean onNavigationItemSelected(MenuItem item) {
Fragment fragment = null;
if (item.isChecked()) {
drawer.closeDrawer(GravityCompat.START);
return false;
}
switch (item.getItemId()) {
case R.id.home: {
fragment = new FragmentMainPage().newInstance("Sample");
break;
}
case R.id.settings:{
Intent intent = new Intent(this,SettingsActivity.class);
startActivity(intent);
break;
}
case R.id.incoming:{
fragment = new FragmentIncomingPage().newInstance("Sample");
break;
}
}
if (fragment != null) {
getSupportFragmentManager()
.beginTransaction().replace(R.id.motherFragments, fragment)
.commit();
item.setChecked(true);
}
drawer.closeDrawer(GravityCompat.START);
return true;
} }
Fragment1 of Navigation drawer
public class FragmentMainPage extends Fragment implements
ViewPager.OnPageChangeListener {
private Toolbar toolbar;
private MainActivity activity;
private TabLayout tabLayout;
private ViewPager viewPager;
String[] names = {
"Sample 1",
"Sample 2"
};
private static FragmentMainPage myInstance;
public static FragmentMainPage newInstance(String testString){
Bundle bundle = new Bundle();
bundle.putString("test",testString);
if(myInstance == null){
myInstance = new FragmentMainPage();
}
myInstance.setArguments(bundle);
return myInstance;
}
#Override
public void onAttach(Context context) {
super.onAttach(context);
activity = ((MainActivity) context);
}
#Override
public void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setHasOptionsMenu(true);
}
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.activity_fragment_main,container,false);
toolbar = (Toolbar) view.findViewById(R.id.toolbar);
activity.setSupportActionBar(toolbar);
activity.setTitle(getResources().getText(R.string.bosh_sahifa));
activity.getSupportActionBar().setHomeAsUpIndicator(R.drawable.ic_menu_white_24dp);
activity.getSupportActionBar().setDisplayHomeAsUpEnabled(true);
viewPager = (ViewPager) view.findViewById(R.id.viewpager);
setupViewpager(viewPager);
tabLayout = (TabLayout) view.findViewById(R.id.tabs);
tabLayout.setupWithViewPager(viewPager);
viewPager.addOnPageChangeListener(this);
setupTabName();
return view;
}
private void setupViewpager(ViewPager viewPager) {
MyAdapter adapter = new MyAdapter(getActivity().getSupportFragmentManager());
adapter.addFragement(new Fragment_home1());
adapter.addFragement(new Fragment_home2());
viewPager.setAdapter(adapter);
}
private void setupTabName() {
tabLayout.getTabAt(0).setText(names[0]);
tabLayout.getTabAt(1).setText(names[1]);
}
#Override
public void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
}
#Override
public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
}
#Override
public void onPageSelected(int position) {
}
#Override
public void onPageScrollStateChanged(int state) {
}
private class MyAdapter extends FragmentPagerAdapter {
private final List<Fragment> mFragmentList = new ArrayList<>();
public MyAdapter(FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int position) {
return mFragmentList.get(position);
}
#Override
public int getCount() {
return mFragmentList.size();
}
public void addFragement(Fragment fragment){
mFragmentList.add(fragment);
}
}
}
Fragment 2 of Navigation drawer
public class FragmentIncomingPage extends Fragment {
private Toolbar toolbar;
private MainActivity activity;
private static FragmentIncomingPage myInstance;
public static FragmentIncomingPage newInstance(String testString){
Bundle bundle = new Bundle();
bundle.putString("test",testString);
if(myInstance == null){
myInstance = new FragmentIncomingPage();
}
myInstance.setArguments(bundle);
return myInstance;
}
#Override
public void onAttach(Context context) {
super.onAttach(context);
activity = ((MainActivity) context);
}
#Override
public void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setHasOptionsMenu(true);
}
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.activity_fragment_incoming,container,false);
toolbar = (Toolbar) view.findViewById(R.id.toolbar);
activity.setSupportActionBar(toolbar);
activity.setTitle(getResources().getText(R.string.Incoming));
activity.getSupportActionBar().setHomeAsUpIndicator(R.drawable.ic_menu_white_24dp);
activity.getSupportActionBar().setDisplayHomeAsUpEnabled(true);
return view;
}
}
Have 3 fragments and swipe to 3rd fragment then back to 1st fragment, the 1st fragment's data is gone?
You can use fragment.addToBackStack(null) method.
like,
FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
ft.replace(R.id.content_frame, A);
ft.addToBackStack(null);
ft.commit();
There is few ways to achieve it.
You can use SharedPreferences to save current Fragment by mViewPager.getCurrentItem() and set it again once you come to the ViewPager activity by navigation drawer button.
Use BaseFragment and implement your fragments from the Base Fragment, keep current visible fragment of the view pager in side the Base Fragment as protected variable.
As Base Fragment which is describe above, You can use Bas Activity class.

android material design tabs fragments not showing up

I have followed the Android codelabs example for material design and I can not get my fragments to display the textedit in each layout please help. Here is my MainActivity.java. Any help would be greatly appreciated, I am new at this as you can probably tell.
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
ViewPager viewPager = (ViewPager) findViewById(R.id.viewpager);
setupViewPager(viewPager);
TabLayout tabs = (TabLayout) findViewById(R.id.tabs);
tabs.setupWithViewPager(viewPager);
NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer);
ActionBar supportActionBar = getSupportActionBar();
if (supportActionBar != null) {
//supportActionBar.setHomeAsUpIndicator(R.drawable.ic_menu_white_24dp);
supportActionBar.setDisplayHomeAsUpEnabled(true);
}
// Set behavior of Navigation drawer
navigationView.setNavigationItemSelectedListener(
new NavigationView.OnNavigationItemSelectedListener() {
// This method will trigger on item Click of navigation menu
#Override
public boolean onNavigationItemSelected(MenuItem menuItem) {
// Set item in checked state
menuItem.setChecked(true);
// TODO: handle navigation
// Closing drawer on item click
mDrawerLayout.closeDrawers();
return true;
}
});
/*
tabs.addTab(tabs.newTab().setText("Dine In"));
tabs.addTab(tabs.newTab().setText("Carry Out"));
tabs.addTab(tabs.newTab().setText("Orders"));
*/
}
private void setupViewPager(ViewPager viewPager) {
Adapter adapter = new Adapter(getSupportFragmentManager());
adapter.addFragment(new DineInFragment(), "Dine In");
adapter.addFragment(new CarryOutFragment(), "Carry Out");
adapter.addFragment(new OrdersFragment(), "Orders");
viewPager.setAdapter(adapter);
}
static class Adapter extends FragmentPagerAdapter {
private final List<Fragment> mFragmentList = new ArrayList<>();
private final List<String> mFragmentTitleList = new ArrayList<>();
public Adapter(FragmentManager manager) {
super(manager);
}
#Override
public Fragment getItem(int position) {
return mFragmentList.get(position);
}
#Override
public int getCount() {
return mFragmentList.size();
}
public void addFragment(Fragment fragment, String title) {
mFragmentList.add(fragment);
mFragmentTitleList.add(title);
}
#Override
public CharSequence getPageTitle(int postion) {
return mFragmentTitleList.get(postion);
}
}

Using both NavigationDrawer and Tabs (Android)

I'm building an app with some tabs and a NavigationDrawer on the side. My problem is I can't display the content of the fragments from my NavigationDrawer : when I click on it nothing happen, I still see my tabs but no new fragment.
I followed those tutorials, one is for the NavigationDrawer and the other one for the tabs, both work separately.
http://www.androidhive.info/2015/04/android-getting-started-with-material-design/
http://www.androidhive.info/2015/09/android-material-design-working-with-tabs/
MainActivity.java (Let me know if you need some more code, I'll edit my post and add it)
public class MainActivity extends AppCompatActivity implements FragmentDrawer.FragmentDrawerListener {
private Toolbar mToolbar;
private FragmentDrawer drawerFragment;
private TabLayout tabLayout;
private ViewPager viewPager;
private int[] tabIcons = {
R.drawable.ic_favorite_white_24dp,
R.drawable.ic_lightbulb_outline_white_24dp,
R.drawable.ic_face_white_24dp
};
private FirebaseAuth mAuth;
private FirebaseAuth.AuthStateListener mAuthListener;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mAuth = FirebaseAuth.getInstance();
mToolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(mToolbar);
Log.i("USER ", mAuth.getCurrentUser().getEmail().toString());
ActionBar actionBar = getSupportActionBar();
if (actionBar != null) {
Log.d("ACTION BAR?", actionBar.toString());
actionBar.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);
// display the first navigation drawer view on app launch
displayView(0);
viewPager = (ViewPager) findViewById(R.id.viewpager);
setupViewPager(viewPager);
tabLayout = (TabLayout) findViewById(R.id.tabs);
tabLayout.setupWithViewPager(viewPager);
setupTabIcons();
mAuthListener = new FirebaseAuth.AuthStateListener() {
#Override
public void onAuthStateChanged(#NonNull FirebaseAuth firebaseAuth) {
FirebaseUser user = firebaseAuth.getCurrentUser();
if (user != null) {
// User is signed in
Log.d("TAG", "onAuthStateChanged:signed_in:" + user.getUid());
} else {
// User is signed out
Log.d("TAG", "onAuthStateChanged:signed_out");
}
// ...
}
};
// ...
}
private void setupTabIcons() {
tabLayout.getTabAt(0).setIcon(tabIcons[0]);
tabLayout.getTabAt(1).setIcon(tabIcons[1]);
tabLayout.getTabAt(2).setIcon(tabIcons[2]);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
#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 HomeFragment();
title = getString(R.string.title_home);
Log.i("DISPLAY VIEW", "HOME FRAGMENT DISPLAYED");
break;
case 1:
fragment = new FriendsFragment();
title = getString(R.string.title_friends);
Log.i("DISPLAY VIEW", "FRIENDS FRAGMENT DISPLAYED");
break;
case 2:
fragment = new MessagesFragment();
title = getString(R.string.title_messages);
Log.i("DISPLAY VIEW", "MSG FRAGMENT DISPLAYED");
break;
default:
break;
}
if (fragment != null) {
FragmentManager fragmentManager = getSupportFragmentManager();
FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
fragmentTransaction.replace(R.id.container_body, fragment);
fragmentTransaction.commit();
// set the toolbar title
getSupportActionBar().setTitle(title);
}
}
private void setupViewPager(ViewPager viewPager) {
ViewPagerAdapter adapter = new ViewPagerAdapter(getSupportFragmentManager());
adapter.addFragment(new OneFragment(), "ONE");
adapter.addFragment(new TwoFragment(), "TWO");
adapter.addFragment(new ThreeFragment(), "THREE");
viewPager.setAdapter(adapter);
}
class ViewPagerAdapter extends FragmentPagerAdapter {
private final List<Fragment> mFragmentList = new ArrayList<>();
private final List<String> mFragmentTitleList = new ArrayList<>();
public ViewPagerAdapter(FragmentManager manager) {
super(manager);
}
#Override
public Fragment getItem(int position) {
return mFragmentList.get(position);
}
#Override
public int getCount() {
return mFragmentList.size();
}
public void addFragment(Fragment fragment, String title) {
mFragmentList.add(fragment);
mFragmentTitleList.add(title);
}
#Override
public CharSequence getPageTitle(int position) {
return mFragmentTitleList.get(position);
}
}
}
I have the displayView() that should display the correct view from the NavigationDrawer but I also have the tabLayout. When I click on the differents items from the NavigationDrawerI have the title changing in the Toolbar but nothing more.
It is very well explained but I'm probably missing something, I know it's probabably a bit of newbie question but since it's my first Android app I guess I'm sort of one. If anyone could give a look and tell me what I should do to make those 2 work together, would be really helpful to me. Thanks!

How to add tabs inside navigation drawer, design error or fragment error

How to add a tab inside the Navigation Drawer ? I getting error when I try to add a tabs inside navigation drawer.
Navigation Drawer:
public class MyFitTrackNavActivity extends AppCompatActivity
implements NavigationView.OnNavigationItemSelectedListener {
FragmentTransaction mFragmentTransaction;
android.support.v4.app.FragmentManager mFragmentManager;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_my_fit_track_nav);
FragmentManager fm = getFragmentManager();
fm.beginTransaction().replace(R.id.content_frame,new HomeFragment()).commit();
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG)
.setAction("Action", null).show();
}
});
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(
this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
drawer.setDrawerListener(toggle);
toggle.syncState();
NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
navigationView.setNavigationItemSelectedListener(this);
}
#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.my_fit_track_nav, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
FragmentManager fm = getFragmentManager();
int id = item.getItemId();
switch (id) {
case R.id.action_settings:
fm.beginTransaction().replace(R.id.content_frame,new SettingFragment()).commit();
return true;
default:
return super.onOptionsItemSelected(item);
}
}
#SuppressWarnings("StatementWithEmptyBody")
#Override
public boolean onNavigationItemSelected(MenuItem item) {
FragmentManager fm = getFragmentManager();
int id = item.getItemId();
if (id == R.id.nav_home)
{
fm.beginTransaction().replace(R.id.content_frame,new HomeFragment()).commit();
}
else if (id == R.id.nav_weight)
{
FragmentTransaction xfragmentTransaction = mFragmentManager.beginTransaction();
xfragmentTransaction.replace(R.id.content_tab, new WeightFragment()).commit();
}
else if (id == R.id.nav_logout)
{
fm.beginTransaction().replace(R.id.content_frame,new LogoutFragment()).commit();
}
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
item.setChecked(true);
setTitle(item.getTitle());
drawer.closeDrawer(GravityCompat.START);
return true;
}
}
Tabs:
public class WeightFragment extends Fragment {
public static TabLayout tabLayout;
public static ViewPager viewPager;
public static int int_items = 3 ;
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.activity_tab_control, container, false);
tabLayout = (TabLayout)rootView.findViewById(R.id.tablayout);
viewPager = (ViewPager)rootView.findViewById(R.id.viewpager);
viewPager.setAdapter(new MyAdapter(getChildFragmentManager()));
tabLayout.post(new Runnable() {
#Override
public void run() {
tabLayout.setupWithViewPager(viewPager);
}
});
return rootView;
}
class MyAdapter extends FragmentPagerAdapter{
public MyAdapter(FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int position)
{
switch (position){
case 0 : return new KeyInWeightF();
case 1 : return new HistoryF();
case 2 : return new AnalysisF();
}
return null;
}
#Override
public int getCount() {
return int_items;
}
#Override
public CharSequence getPageTitle(int position) {
switch (position){
case 0 :
return "Weight";
case 1 :
return "History";
case 2 :
return "Analysis";
}
return null;
}
}
this is onr of the tab fragment in the tab (WeightFragment)
public class KeyInWeightF extends Fragment {
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
return inflater.inflate(R.layout.daily_weight_fragement,null);
}
}
this is my tab design :
<?xml version="1.0" encoding="utf-8"?>
<android.support.design.widget.CoordinatorLayout
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:layout_width="match_parent"
android:layout_height="match_parent"
android:fitsSystemWindows="true"
tools:context="com.example.sam.myfittrack.Tabs.WeightFragment">
<android.support.design.widget.AppBarLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:theme="#style/AppTheme.AppBarOverlay">
<android.support.design.widget.TabLayout
android:id="#+id/tablayout"
android:layout_width="match_parent"
android:layout_height="19dp"
app:tabMode="fixed"
app:tabGravity="fill"
android:layout_below="#+id/toolbar"/>
</android.support.design.widget.AppBarLayout>
<android.support.v4.view.ViewPager
android:id="#+id/viewpager"
android:layout_width="match_parent"
android:layout_height="match_parent"
app:layout_behavior="#string/appbar_scrolling_view_behavior"
android:layout_below="#+id/tablayout"/>
</android.support.design.widget.CoordinatorLayout>
error:
java.lang.NullPointerException
at com.example.sam.myfittrack.MyFitTrackNavActivity.onNavigationItemSelected(MyFitTrackNavActivity.java:118)
at android.support.design.widget.NavigationView$1.onMenuItemSelected(NavigationView.java:150)
at android.support.v7.internal.view.menu.MenuBuilder.dispatchMenuItemSelected(MenuBuilder.java:811)
at android.support.v7.internal.view.menu.MenuItemImpl.invoke(MenuItemImpl.java:153)
at android.support.v7.internal.view.menu.MenuBuilder.performItemAction(MenuBuilder.java:958)
at android.support.design.internal.NavigationMenuPresenter$1.onClick(NavigationMenuPresenter.java:300)
at android.view.View.performClick(View.java:4336)
at android.view.View$PerformClick.run(View.java:17826)
at android.os.Handler.handleCallback(Handler.java:800)
at android.os.Handler.dispatchMessage(Handler.java:100)
at android.os.Looper.loop(Looper.java:194)
at android.app.ActivityThread.main(ActivityThread.java:5434)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:525)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:852)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:619)
at dalvik.system.NativeStart.main(Native Method)

Categories

Resources