I am creating a navigation drawer and every thing is running smoothly: I successfully create it but when I rotate the orientation my current selected fragment automatically attaches to activity after rotation.
I didn't maintain the onSaveInstanceState.
For example: In vertical orientation if I go from
fragmentA -> fragmentB -> fragmentC and rotate the orientation
I am getting fragmentC.
I didn't save the activity state. Result should be fragmentA.
Why is this happening?
BaseFragment.java
public abstract class BaseFragment extends Fragment {
protected static final String ARG_SECTION_NUMBER = "section_number";
abstract public int getFragmentSectionNumber();
}
FragmentA.java
public class FragmentA extends BaseFragment {
public final static String TAG = FragmentA.class.getSimpleName();
public static FragmentA newInstance(int sectionNumber){
FragmentA fragmentA = new FragmentA();
Bundle bundle = new Bundle();
bundle.putInt(ARG_SECTION_NUMBER,sectionNumber);
fragmentA.setArguments(bundle);
return fragmentA;
}
#Override
public void onAttach(Context context) {
super.onAttach(context);
int sectionNumber = getFragmentSectionNumber();
((MainActivity)getActivity()).onSectionAttached(sectionNumber);
}
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View root = inflater.inflate(R.layout.layout_a, null, false);
return root;
}
#Override
public int getFragmentSectionNumber() {
return getArguments().getInt(ARG_SECTION_NUMBER);
}
}
MainActivity.java
public class MainActivity extends AppCompatActivity implements NavigationView.OnNavigationItemSelectedListener {
private FragmentManager fragmentManager;
private ActionBarDrawerToggle toggle;
private DrawerLayout drawer;
private Toolbar toolbar;
private NavigationView navigationView;
private String mTitle;
private int mCurrentPosition;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
init();
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();
}
});
drawer.setDrawerListener(toggle);
toggle.syncState();
navigationView = (NavigationView) findViewById(R.id.nav_view);
if (savedInstanceState == null) {
setFragment(FragmentA.newInstance(R.id.a));
} else {
// int id = savedInstanceState.getInt(Constants.SELECTED_NAVIGATION_ID);
// onSectionAttached(id);
}
navigationView.setNavigationItemSelectedListener(this);
}
private void init() {
toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
fragmentManager = getSupportFragmentManager();
drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
toggle = new ActionBarDrawerToggle(
this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
}
private void setFragment(BaseFragment baseFragment) {
FragmentTransaction transaction = fragmentManager.beginTransaction();
transaction.replace(R.id.fragment_container, baseFragment);
transaction.addToBackStack(null);
transaction.commit();
}
#Override
public void onBackPressed() {
/*DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
if (drawer.isDrawerOpen(GravityCompat.START)) {
drawer.closeDrawer(GravityCompat.START);
return;
} else {
super.onBackPressed();
}
if (fragmentManager.getBackStackEntryCount() <= 0) {
super.onBackPressed();
return;
}
BaseFragment baseFragment = (BaseFragment) fragmentManager.getFragments().get(fragmentManager.getBackStackEntryCount() - 1);
if (baseFragment != null) {
mCurrentPosition = baseFragment.getFragmentSectionNumber();
onSectionAttached(mCurrentPosition);
}*/
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
#SuppressWarnings("StatementWithEmptyBody")
#Override
public boolean onNavigationItemSelected(MenuItem item) {
// Handle navigation view item clicks here.
int id = item.getItemId();
switch (id) {
case R.id.a:
if (mCurrentPosition != R.id.a) {
setFragment(FragmentA.newInstance(R.id.a));
item.setChecked(true);
}
break;
case R.id.b:
if (mCurrentPosition != R.id.b) {
setFragment(FragmentB.newInstance(R.id.b));
item.setChecked(true);
}
break;
case R.id.c:
if (mCurrentPosition != R.id.c) {
setFragment(FragmentC.newInstance(R.id.c));
item.setChecked(true);
}
break;
case R.id.d:
if (mCurrentPosition != R.id.d) {
setFragment(FragmentD.newInstance(R.id.d));
item.setChecked(true);
}
break;
case R.id.e:
if (mCurrentPosition != R.id.e) {
setFragment(FragmentE.newInstance(R.id.e));
item.setChecked(true);
}
break;
default:
break;
}
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
drawer.closeDrawer(GravityCompat.START);
return true;
}
public void onSectionAttached(int number) {
switch (number) {
case R.id.a:
mTitle = "Fragment A";
mCurrentPosition = R.id.a;
break;
case R.id.b:
mTitle = "Fragment B";
mCurrentPosition = R.id.b;
break;
case R.id.c:
mTitle = "Fragment C";
mCurrentPosition = R.id.c;
break;
case R.id.d:
mTitle = "Fragment D";
mCurrentPosition = R.id.d;
break;
case R.id.e:
mTitle = "Fragment E";
mCurrentPosition = R.id.e;
break;
default:
return;
}
if (mTitle != null && getSupportActionBar() != null) {
getSupportActionBar().setTitle(mTitle);
navigationView.getMenu().findItem(mCurrentPosition).setChecked(true);
}
}
private static class Constants {
final static String SELECTED_NAVIGATION_ID = "selected_navigation_id";
}
}
Related
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();
}
}
I read some articles and make a nav drawer and fragments.i want to when I click on items in nav drawer, open fragments layout. but when I click on my fragments, my app crashed and unfortunately has stopped.
Can any one tell me what do I wrong? or what should I do to resolve my problem?
This is my MainActivty.java:
public class MainActivity extends AppCompatActivity {
private DrawerLayout mDrawer;
private Toolbar toolbar;
private NavigationView nvDrawer;
private ActionBarDrawerToggle drawerToggle;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
mDrawer = (DrawerLayout) findViewById(R.id.drawer_layout);
nvDrawer = (NavigationView) findViewById(R.id.nvView);
setupDrawerContent(nvDrawer);
toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
mDrawer = (DrawerLayout) findViewById(R.id.drawer_layout);
drawerToggle = setupDrawerToggle();
mDrawer.addDrawerListener(drawerToggle);
}
private ActionBarDrawerToggle setupDrawerToggle() {
return new ActionBarDrawerToggle(this, mDrawer, 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) {
Fragment fragment = null;
Class fragmentClass;
switch (menuItem.getItemId()) {
case R.id.nav_first_fragment:
fragmentClass = FirstFragment.class;
case R.id.nav_second_fragment:
fragmentClass = SecondFragment.class;
case R.id.nav_third_fragment:
fragmentClass = ThirdFragment.class;
default:
fragmentClass = FirstFragment.class;
}
try {
fragment = (Fragment) fragmentClass.newInstance();
} catch (Exception e) {
e.printStackTrace();
}
FragmentManager fragmentManager = getSupportFragmentManager();
fragmentManager.beginTransaction().replace(R.id.flContent, fragment).commit();
menuItem.setChecked(true);
setTitle(menuItem.getTitle());
mDrawer.closeDrawers();
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home:
mDrawer.openDrawer(GravityCompat.START);
return true;
}
if (drawerToggle.onOptionsItemSelected(item)) {
return true;
}
return super.onOptionsItemSelected(item);
}
#Override
protected void onPostCreate(Bundle savedInstanceState) {
super.onPostCreate(savedInstanceState);
drawerToggle.syncState();
}
#Override
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
drawerToggle.onConfigurationChanged(newConfig);
}
}
This is my firstfragment:
public class FirstFragment extends android.support.v4.app.Fragment {
private static final String ARG_PARAM1 = "param1";
private static final String ARG_PARAM2 = "param2";
private String mParam1;
private String mParam2;
private OnFragmentInteractionListener mListener;
public FirstFragment() {
}
public static FirstFragment newInstance(String param1, String param2) {
FirstFragment fragment = new FirstFragment();
Bundle args = new Bundle();
args.putString(ARG_PARAM1, param1);
args.putString(ARG_PARAM2, param2);
fragment.setArguments(args);
return fragment;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (getArguments() != null) {
mParam1 = getArguments().getString(ARG_PARAM1);
mParam2 = getArguments().getString(ARG_PARAM2);
}
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
return inflater.inflate(R.layout.fragment_first, container, false);
}
public void onButtonPressed(Uri uri) {
if (mListener != null) {
mListener.onFragmentInteraction(uri);
}
}
#Override
public void onAttach(Context context) {
super.onAttach(context);
if (context instanceof OnFragmentInteractionListener) {
mListener = (OnFragmentInteractionListener) context;
} else {
throw new RuntimeException(context.toString()
+ " must implement OnFragmentInteractionListener");
}
}
#Override
public void onDetach() {
super.onDetach();
mListener = null;
}
public interface OnFragmentInteractionListener {
void onFragmentInteraction(Uri uri);
}
}
Call fragment by using below code;
Fragment fragment = new TaskDiscussionFragment();
FragmentManager fm = getActivity().getSupportFragmentManager();
FragmentTransaction ft = fm.beginTransaction();
ft.replace(R.id.flContent, fragment);
ft.commit();
Add the Listener which you are expecting in in FirstFragment in MainActvity and override the interface method like below,
FirstFragment is expecting OnFragmentInteractionListener in your onAttach method.
public class MainActivity extends AppCompatActivity implements OnFragmentInteractionListener{
#Override
public void onFragmentInteraction(Uri uri) {
}
}
I have a really interesting problem with my Navigator menu.
I have no idea why... But I can click on any item from my menu, I don't want to say I click and nothing happened. I really want to say I can't click on any item, all my menu it's like a big image.
I've try to make a new project witch already have Navigation Drawer Activity, of course it works.. but when I've try to copy that code and put on mine.. I have the same problem and vice versa, I've try to put my code into a new project with Navigation Drawer Activity, but again... I can't click on any item.
Here it's one image with my aplication.
Here it's my Main Activity:
public class MainActivity extends Activity implements NavigationDrawerFragment.NavigationDrawerCallbacks, AdapterView.OnItemClickListener {
ArrayList<Trail> arrayTrail;
ListView listViewTrails;
ArrayList<Wonder> arrayWonders1;
ArrayList<Wonder> arrayWonders2;
ArrayList<Wonder> arrayWonders3;
ArrayList<Wonder> arrayWonders4;
private NavigationDrawerFragment mNavigationDrawerFragment;
private CharSequence mTitle;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mNavigationDrawerFragment = (NavigationDrawerFragment) getFragmentManager().findFragmentById(R.id.navigation_drawer);
mTitle = getTitle();
mNavigationDrawerFragment.setUp(R.id.navigation_drawer, (DrawerLayout) findViewById(R.id.drawer_layout));
arrayWonders1 = new ArrayList<>();
arrayWonders2 = new ArrayList<>();
arrayWonders3 = new ArrayList<>();
arrayWonders4 = new ArrayList<>();
arrayWonders1.add(new Wonder("https://risehighershinebrighter.files.wordpress.com/2014/11/magic-of-blue-universe-images.jpg", "Ceva", "100"));
arrayWonders1.add(new Wonder("http://i765.photobucket.com/albums/xx291/just-meller/national%20geografic/Birds-national-geographic-6873734-1600-1200.jpg", "Ceva", "20"));
arrayWonders2.add(new Wonder("hhttp://www.freestockphotos.name/wallpaper-original/wallpapers/download-images-of-gentle-dogs-6866.jpg", "Ceva", "400"));
arrayWonders2.add(new Wonder("http://www.planwallpaper.com/static/images/desktop-year-of-the-tiger-images-wallpaper.jpg", "Ceva", "200"));
arrayWonders3.add(new Wonder("http://hdwallnpics.com/wp-content/gallery/hd-tiger-images/tigers-wallpapers-hd.jpg", "Ceva", "100"));
arrayWonders3.add(new Wonder("http://imgscenter.com/images/2014/09/13/6-autumn-nature-sandbox-images_2053316.jpg", "Ceva", "100"));
arrayWonders4.add(new Wonder("http://www.tollywooddaily.com/wp-content/uploads/2015/05/HORIZONTAL-BABY-HIGHRES-EMPTY.jpg", "Ceva", "100"));
arrayWonders4.add(new Wonder("http://www.hdwallpapersimages.com/wp-content/uploads/2014/01/Winter-Tiger-Wild-Cat-Images.jpg", "Ceva", "100"));
arrayTrail = new ArrayList<>();
Trail audi = new Trail("http://www.hdwallpapersimages.com/wp-content/uploads/2014/01/Winter-Tiger-Wild-Cat-Images.jpg", "Paris", "Popular Destination", "htrhetgftrwfrec", "Story", arrayWonders1);
Trail opel = new Trail("http://www.gettyimages.com/gi-resources/images/CreativeImages/Hero-527920799.jpg", "Romania", "Popular Destination", "fewfwefwefWgfeg", "Story", arrayWonders2);
Trail mercedes = new Trail("http://blog.jimdo.com/wp-content/uploads/2014/01/tree-247122.jpg", "Italia", "Popular Destination", "gtrhrthtrhrw", "Story", arrayWonders3);
Trail ferrari = new Trail("http://saturn.jpl.nasa.gov/multimedia/images/moons/images/PIA07759.jpg", "Roma", "Popular Destination", "dajfuisndfisndfs", "Story", arrayWonders4);
Trail fiesta = new Trail("http://www.quicksprout.com/images/foggygoldengatebridge.jpg", "Bucuresti", "Popular Destination", "regehgtrhrjhjy", "Story", arrayWonders1);
Trail porshe = new Trail("http://3.bp.blogspot.com/-rZmCIp0C-hQ/Tx6aCFeweoI/AAAAAAAAAnQ/WqIEVBTIzRk/s1600/Cool-Tiger-Wallpaper-1920x1080-HD.jpg", "Luxemburg", "Popular Destination", "Ffdsjifsdfmskodmf", "Story", arrayWonders2);
arrayTrail.add(audi);
arrayTrail.add(opel);
arrayTrail.add(mercedes);
arrayTrail.add(ferrari);
arrayTrail.add(fiesta);
arrayTrail.add(porshe);
listViewTrails = (ListView) findViewById(R.id.list_trails);
ListTailsAdapter adapter = new ListTailsAdapter(this, arrayTrail);
listViewTrails.setAdapter(adapter);
listViewTrails.setOnItemClickListener(this);
}
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Trail selectedTrail = arrayTrail.get(position);
Intent intent = new Intent(this, TrailActivity.class);
intent.putExtra("trail", selectedTrail);
startActivity(intent);
}
#Override
public void onNavigationDrawerItemSelected(int position) {
FragmentManager fragmentManager = getFragmentManager();
fragmentManager.beginTransaction().replace(R.id.container, PlaceholderFragment.newInstance(position + 1)).commit();
}
public void onSectionAttached(int number) {
switch (number) {
case 1:
mTitle = getString(R.string.title_section1);
break;
case 2:
mTitle = getString(R.string.title_section2);
break;
case 3:
mTitle = getString(R.string.title_section3);
break;
}
}
public void restoreActionBar() {
ActionBar actionBar = getActionBar();
actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_STANDARD);
actionBar.setDisplayShowTitleEnabled(false);
actionBar.setTitle(mTitle);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
if (!mNavigationDrawerFragment.isDrawerOpen()) {
getMenuInflater().inflate(R.menu.main, menu);
restoreActionBar();
return true;
}
return super.onCreateOptionsMenu(menu);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
if (id == R.id.main_menu_search) {
ArrayList<Trail> trails = arrayTrail;
Intent intent = new Intent(this, SearchActivity.class);
intent.putExtra("trailsSearch", trails);
startActivity(intent);
return true;
}
return super.onOptionsItemSelected(item);
}
public static class PlaceholderFragment extends Fragment {
private static final String ARG_SECTION_NUMBER = "section_number";
public static PlaceholderFragment newInstance(int sectionNumber) {
PlaceholderFragment fragment = new PlaceholderFragment();
Bundle args = new Bundle();
args.putInt(ARG_SECTION_NUMBER, sectionNumber);
fragment.setArguments(args);
return fragment;
}
public PlaceholderFragment() {
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_main, container, false);
return rootView;
}
#Override
public void onAttach(Activity activity) {
super.onAttach(activity);
((MainActivity) activity).onSectionAttached(getArguments().getInt(ARG_SECTION_NUMBER));
}
}
}
And here it Navigation Drawer Fragment class:
public class NavigationDrawerFragment extends Fragment {
private static final String STATE_SELECTED_POSITION = "selected_navigation_drawer_position";
private static final String PREF_USER_LEARNED_DRAWER = "navigation_drawer_learned";
private NavigationDrawerCallbacks mCallbacks;
private ActionBarDrawerToggle mDrawerToggle;
private DrawerLayout mDrawerLayout;
private ListView mDrawerListView;
private View mFragmentContainerView;
private int mCurrentSelectedPosition = 0;
private boolean mFromSavedInstanceState;
private boolean mUserLearnedDrawer;
public NavigationDrawerFragment() {
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(getActivity());
mUserLearnedDrawer = sp.getBoolean(PREF_USER_LEARNED_DRAWER, false);
if (savedInstanceState != null) {
mCurrentSelectedPosition = savedInstanceState.getInt(STATE_SELECTED_POSITION);
mFromSavedInstanceState = true;
}
selectItem(mCurrentSelectedPosition);
}
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
setHasOptionsMenu(true);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
mDrawerListView = (ListView) inflater.inflate(
R.layout.fragment_navigation_drawer, container, false);
mDrawerListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
selectItem(position);
}
});
mDrawerListView.setAdapter(new ArrayAdapter<String>(
getActionBar().getThemedContext(),
android.R.layout.simple_list_item_activated_1,
android.R.id.text1,
new String[]{
getString(R.string.categori_1),
getString(R.string.categori_2),
getString(R.string.categori_3),
}));
mDrawerListView.setItemChecked(mCurrentSelectedPosition, true);
return mDrawerListView;
}
public boolean isDrawerOpen() {
return mDrawerLayout != null && mDrawerLayout.isDrawerOpen(mFragmentContainerView);
}
public void setUp(int fragmentId, DrawerLayout drawerLayout) {
mFragmentContainerView = getActivity().findViewById(fragmentId);
mDrawerLayout = drawerLayout;
mDrawerLayout.setDrawerShadow(R.drawable.drawer_shadow, GravityCompat.START);
ActionBar actionBar = getActionBar();
actionBar.setDisplayHomeAsUpEnabled(true);
actionBar.setHomeButtonEnabled(true);
mDrawerToggle = new ActionBarDrawerToggle(
getActivity(),
mDrawerLayout,
R.drawable.ic_drawer,
R.string.navigation_drawer_open,
R.string.navigation_drawer_close
) {
#Override
public void onDrawerClosed(View drawerView) {
super.onDrawerClosed(drawerView);
if (!isAdded()) {
return;
}
getActivity().invalidateOptionsMenu();
}
#Override
public void onDrawerOpened(View drawerView) {
super.onDrawerOpened(drawerView);
if (!isAdded()) {
return;
}
if (!mUserLearnedDrawer) {
mUserLearnedDrawer = true;
SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(getActivity());
sp.edit().putBoolean(PREF_USER_LEARNED_DRAWER, true).apply();
}
getActivity().invalidateOptionsMenu(); // calls onPrepareOptionsMenu()
}
};
if (!mUserLearnedDrawer && !mFromSavedInstanceState) {
mDrawerLayout.openDrawer(mFragmentContainerView);
}
mDrawerLayout.post(new Runnable() {
#Override
public void run() {
mDrawerToggle.syncState();
}
});
mDrawerLayout.setDrawerListener(mDrawerToggle);
}
private void selectItem(int position) {
mCurrentSelectedPosition = position;
if (mDrawerListView != null) {
mDrawerListView.setItemChecked(position, true);
}
if (mDrawerLayout != null) {
mDrawerLayout.closeDrawer(mFragmentContainerView);
}
if (mCallbacks != null) {
mCallbacks.onNavigationDrawerItemSelected(position);
}
}
#Override
public void onAttach(Activity activity) {
super.onAttach(activity);
try {
mCallbacks = (NavigationDrawerCallbacks) activity;
} catch (ClassCastException e) {
throw new ClassCastException("Activity must implement NavigationDrawerCallbacks.");
}
}
#Override
public void onDetach() {
super.onDetach();
mCallbacks = null;
}
#Override
public void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
outState.putInt(STATE_SELECTED_POSITION, mCurrentSelectedPosition);
}
#Override
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
mDrawerToggle.onConfigurationChanged(newConfig);
}
#Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
if (mDrawerLayout != null && isDrawerOpen()) {
inflater.inflate(R.menu.main, menu);
showGlobalContextActionBar();
}
super.onCreateOptionsMenu(menu, inflater);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
if (mDrawerToggle.onOptionsItemSelected(item)) {
return true;
}
return super.onOptionsItemSelected(item);
}
private void showGlobalContextActionBar() {
ActionBar actionBar = getActionBar();
actionBar.setDisplayShowTitleEnabled(true);
actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_STANDARD);
actionBar.setTitle(R.string.app_name);
}
private ActionBar getActionBar() {
return getActivity().getActionBar();
}
public static interface NavigationDrawerCallbacks {
void onNavigationDrawerItemSelected(int position);
}
}
So if anyone of you guys have any idea... Please tell me, I really need to fix it as soon as possible and in this moment I don't have any idea how..
Thx for your help :)
this code work for me
public class MyDrawer extends AppCompatActivity {
ActionBarDrawerToggle toggle;
// other code
super.setContentView(fullLayout);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
//setSupportActionBar(toolbar);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setHomeButtonEnabled(true);
final DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout3);
toggle = new ActionBarDrawerToggle(
this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
drawer.setDrawerListener(toggle);
toggle.syncState();
final NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
navigationView.setNavigationItemSelectedListener(new NavigationView.OnNavigationItemSelectedListener() {
#Override
public boolean onNavigationItemSelected(MenuItem menuItem) {
drawer.closeDrawers();
int itemId = menuItem.getItemId();
//Toast.makeText(getApplicationContext(), menuItem.getTitle().toString(),
// Toast.LENGTH_LONG).show();
int id = menuItem.getItemId();
if (id == R.id.nav_camara) {
update();
// Handle the camera action
} else if (id == R.id.nav_gallery) {
Intent intent = new Intent(getApplicationContext(), AndroidListViewCursorAdaptorActivity.class);
startActivity(intent);
// } else if (id == R.id.nav_slideshow) {
} else if (id == R.id.nav_manage) {
Intent intent = new Intent(getApplicationContext(), Manage.class);
startActivity(intent);
} else if (id == R.id.nav_about) {
Intent intent = new Intent(getApplicationContext(), About.class);
startActivity(intent);
}
else if (id == R.id.nav_cantect) {
Intent intent = new Intent(getApplicationContext(), AboutCantect.class);
startActivity(intent);
}
//navigationView.getMenu().findItem(R.id.drawer_5_reasons).setChecked(true);
return true;
}
});
}
#Override
public boolean onOptionsItemSelected(MenuItem item)
{
if (toggle.onOptionsItemSelected(item))
{
return true;
}
return super.onOptionsItemSelected(item);
}
android developers please help, I Have viewpager with fragments, when i slide in the pages and reached the last page and then when i return to the first page again the fragment of the first page loads its default display.Please help..here is my code in MainActivity
public class MainActivity extends AppCompatActivity {
private ActionBarDrawerToggle actionBarDrawerToggle;
private DrawerLayout drawerLayout;
private ListView navList;
private FragmentManager fragmentManager;
private FragmentTransaction fragmentTransaction;
private ActionBar actionBar;
private ViewPager pager;
private Menu menu;
private float lastTranslate = 0.0f;
private FrameLayout mainframe, galleryframe;
private Frag_Gallery fragGallery;
private Frag_Create fragCreate;
private Frag_Account fragAccount;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
pager = (ViewPager) findViewById(R.id.viewPager);
mainframe = (FrameLayout) findViewById(R.id.fragmentholder);
galleryframe = (FrameLayout) findViewById(R.id.galleryholder);
pager.setAdapter(new MyPagerAdapter(getSupportFragmentManager()));
ColorDrawable colorDrawable = new ColorDrawable(Color.parseColor("#0b115e"));
Main_Menu Menu_data[] = new Main_Menu[]
{
new Main_Menu(R.mipmap.gallery_icon, "Gallery"),
new Main_Menu(R.mipmap.create_icon, "Create Your Own"),
new Main_Menu(R.mipmap.account_icon, "My Account"),
new Main_Menu(R.mipmap.contact_icon, "Contact Us")
};
MainMenuAdapter adapter = new MainMenuAdapter(this,
R.layout.listviewmain_item_row, Menu_data);
drawerLayout = (DrawerLayout) findViewById(R.id.drawerlayout);
navList = (ListView) findViewById(R.id.navList);
View header = (View) getLayoutInflater().inflate(R.layout.listviewmain_header_row, null);
navList.addHeaderView(header);
navList.setAdapter(adapter);
navList.setDivider(null);
navList.setChoiceMode(ListView.CHOICE_MODE_SINGLE);
navList.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
loadSelection(position);
drawerLayout.closeDrawer(navList);
}
});
actionBarDrawerToggle = new ActionBarDrawerToggle(this, drawerLayout, R.string.opendrawer, R.string.closedrawer);
drawerLayout.setDrawerListener(actionBarDrawerToggle);
actionBar = getSupportActionBar();
actionBar.setDisplayShowHomeEnabled(true);
actionBar.setDisplayHomeAsUpEnabled(true);
actionBar.setBackgroundDrawable(colorDrawable);
actionBar.setTitle("");
fragmentManager = getSupportFragmentManager();
loadSelection(0);
pager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
#Override
public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
}
#Override
public void onPageSelected(int pos) {
switch (pos) {
case 0:
menu.getItem(0).setIcon(R.mipmap.gallery_icon);
menu.getItem(1).setIcon(R.mipmap.create_icon_off);
menu.getItem(2).setIcon(R.mipmap.account_icon_off);
break;
case 1:
menu.getItem(0).setIcon(R.mipmap.gallery_icon_off);
menu.getItem(1).setIcon(R.mipmap.create_icon);
menu.getItem(2).setIcon(R.mipmap.account_icon_off);
break;
case 2:
menu.getItem(0).setIcon(R.mipmap.gallery_icon_off);
menu.getItem(1).setIcon(R.mipmap.create_icon_off);
menu.getItem(2).setIcon(R.mipmap.account_icon);
break;
}
}
#Override
public void onPageScrollStateChanged(int state) {
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
this.menu = menu;
getMenuInflater().inflate(R.menu.menu_main, menu);
menu.getItem(0).setIcon(R.mipmap.gallery_icon);
menu.getItem(1).setIcon(R.mipmap.create_icon_off);
menu.getItem(2).setIcon(R.mipmap.account_icon_off);
return true;
}
private void loadSelection(int i) {
switch (i) {
case 1:
actionBar.setTitle("Gallery");
pager.setCurrentItem(0, true);
break;
case 2:
actionBar.setTitle("Design");
pager.setCurrentItem(1, true);
break;
case 3:
actionBar.setTitle("Account");
pager.setCurrentItem(2, true);
break;
case 4:
actionBar.setTitle("Contact us");
break;
default:
actionBar.setTitle("");
break;
}
}
#Override
protected void onPostCreate(Bundle savedInstanceState) {
super.onPostCreate(savedInstanceState);
actionBarDrawerToggle.syncState();
}
#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 == android.R.id.home) {
if (drawerLayout.isDrawerOpen(navList)) {
drawerLayout.closeDrawer(navList);
} else {
drawerLayout.openDrawer(navList);
}
}
return super.onOptionsItemSelected(item);
}
private class MyPagerAdapter extends FragmentPagerAdapter {
private Fragment fragment;
public MyPagerAdapter(FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int pos) {
fragment = new Fragment();
switch (pos) {
case 0:
fragment = new Frag_Gallery();
break;
case 1:
fragment = new Frag_Create();
break;
case 2:
fragment = new Frag_Account();
default:
break;
}
return fragment;
}
#Override
public int getCount() {
return 3;
}
}
}
use
pager.setOffscreenPageLimit(X);
where X is the count of the pages you want to save so the ViewPager wont rebuild them.
I want to implement Left & Right Side Slider Menu so I have set Right Side Slider in NavigationDrawerSlider which already have Left Side Slider by Default.
I am using ActionBarSherLock for this to support Application from Api 8. Slider is working fine but issue is that ActionBar is not showing Title.
Please help me to solve this issue. One more thing, When I Click on ImageView, It also fires ActionBarDrawerToggle. So, how to prevent this also ?
My Code:
public class MainActivity extends SherlockFragmentActivity {
private DrawerLayout mDrawerLayout;
private ListView mDrawerList_Left;
private ListView mDrawerList_Right;
private ActionBarDrawerToggle mDrawerToggle;
private ActionBar actionBar_Right;
private ArrayList<NavDrawerItem> navDrawerItems_Left;
private ArrayList<NavDrawerItem> navDrawerItems_Right;
private CharSequence mDrawerTitle_Left;
private CharSequence mTitle_Left;
private CharSequence mDrawerTitle_Right;
private CharSequence mTitle_Right;
private String[] mFragmentTitles_Left;
private String[] mFragmentTitles_Right;
private TypedArray navMenuIcons_Left;
private TypedArray navMenuIcons_Right;
private NavDrawerListAdapter adapter_Left;
private NavDrawerListAdapter adapter_Right;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mTitle_Left = mDrawerTitle_Left = getTitle();
mFragmentTitles_Left = getResources().getStringArray(
R.array.nav_drawer_items);
mFragmentTitles_Right = getResources().getStringArray(
R.array.nav_drawer_items_right);
navMenuIcons_Left = getResources().obtainTypedArray(
R.array.nav_drawer_icons);
navMenuIcons_Right = getResources().obtainTypedArray(
R.array.nav_drawer_icons_right);
mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
mDrawerList_Left = (ListView) findViewById(R.id.list_left_slidermenu);
mDrawerList_Right = (ListView) findViewById(R.id.list_right_slidermenu);
actionBar_Right = getSupportActionBar();
actionBar_Right.setCustomView(R.layout.right_menu);
actionBar_Right.setDisplayShowTitleEnabled(true);
actionBar_Right.setDisplayShowCustomEnabled(true);
navDrawerItems_Left = new ArrayList<NavDrawerItem>();
navDrawerItems_Right = new ArrayList<NavDrawerItem>();
// Left Side Menus...
// Home...
navDrawerItems_Left.add(new NavDrawerItem(mFragmentTitles_Left[0],
navMenuIcons_Left.getResourceId(0, -1)));
navMenuIcons_Left.recycle();
// Right Side Menus...
// Edit Profile...
navDrawerItems_Right.add(new NavDrawerItem(mFragmentTitles_Right[0],
navMenuIcons_Right.getResourceId(0, -1)));
// Change Password...
navDrawerItems_Right.add(new NavDrawerItem(mFragmentTitles_Right[1],
navMenuIcons_Right.getResourceId(1, -1)));
navMenuIcons_Right.recycle();
mDrawerList_Left
.setOnItemClickListener(new DrawerItemClickListener_Left());
mDrawerList_Right
.setOnItemClickListener(new DrawerItemClickListener_Right());
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setHomeButtonEnabled(true);
adapter_Left = new NavDrawerListAdapter(getApplicationContext(),
navDrawerItems_Left);
mDrawerList_Left.setAdapter(adapter_Left);
mDrawerToggle = new ActionBarDrawerToggle(this, mDrawerLayout,
R.drawable.ic_drawer, R.string.app_name, R.string.app_name);
adapter_Right = new NavDrawerListAdapter(getApplicationContext(),
navDrawerItems_Right);
mDrawerList_Right.setAdapter(adapter_Right);
ImageView imgRight = (ImageView) findViewById(R.id.imgRightMenu);
imgRight.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
if (mDrawerLayout.isDrawerOpen(mDrawerList_Right)) {
mDrawerLayout.closeDrawer(mDrawerList_Right);
setTitle(mTitle_Right);
} else {
mDrawerLayout.openDrawer(mDrawerList_Right);
mDrawerLayout.closeDrawer(mDrawerList_Left);
setTitle(mDrawerTitle_Right);
}
}
});
mDrawerLayout.setDrawerListener(mDrawerToggle);
if (savedInstanceState == null) {
selectItem_Left(0);
}
}
#Override
public boolean onPrepareOptionsMenu(Menu menu) {
// boolean drawerOpen = mDrawerLayout.isDrawerOpen(mDrawerList);
return super.onPrepareOptionsMenu(menu);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
// getSupportMenuInflater().inflate(R.menu.main, menu);
return true;
}
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home:
if (mDrawerLayout.isDrawerOpen(mDrawerList_Left)) {
mDrawerLayout.closeDrawer(mDrawerList_Left);
setTitle(mTitle_Left);
} else {
mDrawerLayout.openDrawer(mDrawerList_Left);
mDrawerLayout.closeDrawer(mDrawerList_Right);
setTitle(mDrawerTitle_Left);
}
return true;
default:
return super.onOptionsItemSelected(item);
}
}
private class DrawerItemClickListener_Left implements
ListView.OnItemClickListener {
#Override
public void onItemClick(AdapterView<?> parent, View v, int position,
long id) {
selectItem_Left(position);
}
}
private void selectItem_Left(int position) {
Fragment newFragment = new Home();
FragmentManager fm = getSupportFragmentManager();
switch (position) {
case 0:
newFragment = new Home();
break;
}
fm.beginTransaction().replace(R.id.frame_container, newFragment)
.commit();
mDrawerList_Left.setItemChecked(position, true);
setTitle(mFragmentTitles_Left[position]);
mDrawerLayout.closeDrawer(mDrawerList_Left);
}
private class DrawerItemClickListener_Right implements
ListView.OnItemClickListener {
#Override
public void onItemClick(AdapterView<?> parent, View v, int position,
long id) {
selectItem_Right(position);
}
}
private void selectItem_Right(int position) {
Fragment newFragment = new EditProfile();
FragmentManager fm = getSupportFragmentManager();
switch (position) {
case 0:
newFragment = new EditProfile();
break;
case 1:
newFragment = new ChangePassword();
break;
}
fm.beginTransaction().replace(R.id.frame_container, newFragment)
.commit();
mDrawerList_Right.setItemChecked(position, true);
setTitle(mFragmentTitles_Right[position]);
mDrawerLayout.closeDrawer(mDrawerList_Right);
}
#Override
protected void onPostCreate(Bundle savedInstanceState) {
super.onPostCreate(savedInstanceState);
mDrawerToggle.syncState();
}
#Override
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
mDrawerToggle.onConfigurationChanged(newConfig);
}
}
I have figured out that It is not showing title because of
actionBar_Right = getSupportActionBar();
actionBar_Right.setCustomView(R.layout.right_menu);
actionBar_Right.setDisplayShowTitleEnabled(true);
actionBar_Right.setDisplayShowCustomEnabled(true);
What to do for this ?
For showing the title in the ActionBar setTitle must be overridden:
#Override
public void setTitle(CharSequence title)
{
this.title = title;
getSupportActionBar().setTitle(title);
}