I have one activity, inside I have toolbar and navigationView.
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.start_page_activity);
getFragment(new MainFragment());
mToolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(mToolbar);
mNavigationView = (NavigationView) findViewById(R.id.main_drawer);
mNavigationView.setNavigationItemSelectedListener(this);
mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer_widget);
drawerToggle
= new ActionBarDrawerToggle(this, mDrawerLayout, mToolbar, R.string.drawer_open, R.string.drawer_close);
mDrawerLayout.setDrawerListener(drawerToggle);
}
#Override
protected void onPostCreate(Bundle savedInstanceState) {
super.onPostCreate(savedInstanceState);
Log.i("StartPageActivity", "onPostCreate");
drawerToggle.syncState();
}
When starting activity at first called Main Fragment.
When I select item in NavigationView opens new Fragment.
when appear second fragment, inside I use
ActionBar a = ((AppCompatActivity) getActivity()).getSupportActionBar();
a.setDisplayHomeAsUpEnabled(true);
Up arrow appeared, but when I click on this Up arrow opens NavigationVIEW!!!
in fragment inside onOptionsItemSelected I HAVE
case android.R.id.home:{
Log.i("One", "Dude");
}
The program does not comply with this code. It does not come to it. I think the problem inside onCreate (activity). Maybe it conflict between ActionBarDrawerToggle, NavigationView and Toolbar.
ADD second fragment
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setHasOptionsMenu(true);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.reminder_list_fragment, container, false);
getActivity().setTitle("Fragment1");
mRecyclerView = (RecyclerView)v. findViewById(R.id.my_recycler_view);
//{RecyclerAdapter}
ActionBar a = ((AppCompatActivity) getActivity()).getSupportActionBar();
a.setDisplayHomeAsUpEnabled(true);
a.setHomeButtonEnabled(true);
return v;
}
#Override
public void onResume() {
super.onResume();
mRecyclerView.getAdapter().notifyDataSetChanged();
}
#Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
super.onCreateOptionsMenu(menu, inflater);
menu.clear();
inflater.inflate(R.menu.reminder_toolbar, menu);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
Log.d("Testing", "ID == " + id);
switch (id) {
case R.id.add_information : {
Forget f = new Forget();
ForgetLab.get(getActivity()).addForget(f);
FragmentManager fm = getFragmentManager();
Fragment mFragment = fm.findFragmentById(R.id.fragment_container);
Bundle bundle = new Bundle();
bundle.putSerializable(ReminderFragment.EXTRA_FORGET_ID, f.getId());
if (mFragment != null) {
mFragment = new ReminderPagerFragment();
mFragment.setArguments(bundle);
fm.beginTransaction().addToBackStack(null)
.replace(R.id.fragment_container, mFragment)
.commit();
}
return true;
}
case android.R.id.home:{
Log.i("One", "Dude");
}
}
return super.onOptionsItemSelected(item);
}
You should overRide onOptionsItemSelected(MenuItem item) and setHasOptionsMenu(true) should be called inside onCreate(Bundle savedInstanceState)
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setHasOptionsMenu(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 == android.R.id.home) {
getActivity().onBackPressed();
}
return super.onOptionsItemSelected(item);
} I hope this works....
Use this complete example.
public abstract class BaseActivity extends AppCompatActivity{
protected Toolbar toolbar;
protected User mMe;
protected DrawerLayout mDrawerLayout;
protected ActionBarDrawerToggle drawerToggle;
#Override
public void setContentView(int layoutResID) {
super.setContentView(layoutResID);
mMe = SessionUtils.getUser();
if (mMe == null) {
return;
}
initToolbar();
initInstances();
}
private void initToolbar() {
toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
}
private void initInstances() {
mDrawerLayout = (DrawerLayout) findViewById(R.id.drawerLayout);
if (mDrawerLayout != null) {
final NavigationView navigationView = (NavigationView) findViewById(R.id.navigation);
ImageView profileImage = (ImageView) navigationView.findViewById(R.id.profileImage);
profileImage.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
ActivityUtils.launchProfileActivity(BaseActivity.this, SessionUtils.getUser());
}
});
TextView name = (TextView) navigationView.findViewById(R.id.name);
final String fullName = StringUtils.getFullName(mMe.firstName, mMe.lastName);
name.setText(fullName);
GlideUtils.load(profileImage, mMe.getImage(), GlideUtils.getCircularFallbackDrawable(this, fullName), new CircleTransformGlide(this));
navigationView.setNavigationItemSelectedListener(new NavigationView.OnNavigationItemSelectedListener() {
#Override
public boolean onNavigationItemSelected(MenuItem menuItem) {
int itemId = menuItem.getItemId();
switch (itemId) {
case R.id.messages:
ActivityUtils.launchMessagesFragment(BaseActivity.this);
LogUtils.LOGD(">>Menu", "Messages");
break;
// case R.id.notification:
// LogUtils.LOGD(">>Menu", "Notification");
// break;
case R.id.friends:
LogUtils.LOGD(">>Menu", "find friends");
ActivityUtils.launchFriendsActivity(BaseActivity.this);
break;
case R.id.termsOfService:
ActivityUtils.launchTermsOfServiceFragment(BaseActivity.this);
break;
case R.id.friendsRrequests:
LogUtils.LOGD(">>Menu", "friendsRrequests");
ActivityUtils.launchFriendsRequests(BaseActivity.this);
break;
case R.id.logout:
LogUtils.LOGD(">>Menu", "Logout");
DialogUtils.LogoutConfirmDialogFragment logoutConfirmDialogFragment = new DialogUtils.LogoutConfirmDialogFragment();
logoutConfirmDialogFragment.show(getSupportFragmentManager(), "Logout Confirmation Fragment");
// LoginManager.reset(BaseActivity.this);
break;
}
// menuItem.setChecked(true);
// if (R.id.friends == itemId) {
// mDrawerLayout.postDelayed(new Runnable() {
// #Override
// public void run() {
// mDrawerLayout.closeDrawers();
// }
// }, 1000);
// } else {
// mDrawerLayout.closeDrawers();
// }
return true;
}
});
drawerToggle = new DrawerToggle(this, mDrawerLayout, toolbar, R.string.app_name, R.string.app_name, new DrawerToggleListener() {
#Override
public void OnDrawerClose() {
}
#Override
public void OnDrawerOpen() {
}
});
mDrawerLayout.setDrawerListener(drawerToggle);
final ActionBar supportActionBar = getSupportActionBar();
if (supportActionBar != null) {
supportActionBar.setHomeButtonEnabled(true);
supportActionBar.setDisplayHomeAsUpEnabled(true);
}
}
}
#Override
public void onPostCreate(Bundle savedInstanceState) {
super.onPostCreate(savedInstanceState);
if (drawerToggle != null)
drawerToggle.syncState();
}
#Override
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
if (drawerToggle != null)
drawerToggle.onConfigurationChanged(newConfig);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
return (drawerToggle != null && drawerToggle.onOptionsItemSelected(item)) || super.onOptionsItemSelected(item);
}
#Override
public void onBackPressed() {
if (mDrawerLayout != null && mDrawerLayout.isDrawerOpen(GravityCompat.START)) {
mDrawerLayout.closeDrawer(GravityCompat.START);
} else {
super.onBackPressed();
}
}
private static class DrawerToggle extends ActionBarDrawerToggle {
DrawerToggleListener mToggleListener;
public DrawerToggle(Activity activity, DrawerLayout drawerLayout, Toolbar toolbar, int openDrawerContentDescRes, int closeDrawerContentDescRes, DrawerToggleListener toggleListener) {
super(activity, drawerLayout, toolbar, openDrawerContentDescRes, closeDrawerContentDescRes);
mToggleListener = toggleListener;
}
#Override
public void onDrawerClosed(View drawerView) {
super.onDrawerClosed(drawerView);
mToggleListener.OnDrawerClose();
}
#Override
public void onDrawerOpened(View drawerView) {
super.onDrawerOpened(drawerView);
mToggleListener.OnDrawerOpen();
}
}
private static abstract class DrawerToggleListener {
public abstract void OnDrawerClose();
public abstract void OnDrawerOpen();
}
}
You Main activity must extends BaseActivity
public class MainActivity extends BaseActivity {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (!LoginManager.isFirstFlowFinished(this)) {
LoginManager.launchCurrentFragment(this);
finish();
return;
}
Intent intent = getIntent();
handleIntent(intent);
setContentView(R.layout.activity_main_new);
LogUtils.LOGD(">>Intent", "onCreate");
}
#Override
public void onResume() {
super.onResume();
LocationTracker.promptIfNeededForEnableLocation(this);
CommonUtils.checkIfPlayServicesNeedToUpdate(this);
AppEventsLogger.activateApp(this);
}
#Override
protected void onPause() {
super.onPause();
AppEventsLogger.deactivateApp(this);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.menu_search, menu);
return super.onCreateOptionsMenu(menu);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.action_search_icon:
ActivityUtils.launchSearchActivity(this);
break;
}
return true;
}
#Override
public void onBackPressed() {
super.onBackPressed();
}
#Override
protected void onNewIntent(Intent intent) {
super.onNewIntent(intent);
LogUtils.LOGD(">>Intent", "on handle Intent");
handleIntent(intent);
}
}
And here is activity_main_new.xml
<android.support.v4.widget.DrawerLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/drawerLayout"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:fitsSystemWindows="true"
tools:context=".MainActivity">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<android.support.v7.widget.Toolbar
android:id="#+id/toolbar"
android:layout_width="match_parent"
android:layout_height="?actionBarSize"
android:minHeight="?actionBarSize"
android:background="?colorPrimary"
app:layout_collapseMode="pin"
app:popupTheme="#style/ThemeOverlay.AppCompat.Light"
app:theme="#style/ThemeOverlay.AppCompat.Dark.ActionBar" >
<TextView
android:textColor="#color/white"
android:textSize="18sp"
android:textStyle="bold"
android:text="Friends Locator"
android:gravity="center"
android:layout_width="match_parent"
android:layout_height="match_parent" />
</android.support.v7.widget.Toolbar>
<fragment
android:orientation="vertical"
android:id="#+id/viewPager"
android:name="com.macrotechnologies.friendslocator.ui.NearBySuggestionsFragment"
android:tag="com.macrotechnologies.friendslocator.ui.NearBySuggestionsFragment"
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="1" />
</LinearLayout>
<android.support.design.widget.NavigationView
android:id="#+id/navigation"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:layout_gravity="start"
app:headerLayout="#layout/nav_header"
app:itemIconTint="#color/nav_item_icon_tint_color"
app:itemTextColor="#color/nav_item_text_color"
app:menu="#menu/navigation_drawer_items" />
and Navigation Menu item is as:
<?xml version="1.0" encoding="utf-8"?>
<group android:checkableBehavior="none">
<item
android:id="#+id/friends"
android:icon="#drawable/ic_navigation_chevron_right"
android:title="#string/friends_caps" />
<item
android:id="#+id/messages"
android:icon="#drawable/ic_navigation_chevron_right"
android:title="#string/messages" />
<item
android:id="#+id/friendsRrequests"
android:icon="#drawable/ic_navigation_chevron_right"
android:title="#string/friendsRequests" />
<!-- <item
android:id="#+id/notification"
android:icon="#drawable/ic_navigation_chevron_right"
android:title="#string/notifications" />-->
<!--<item-->
<!--android:id="#+id/about"-->
<!--android:icon="#drawable/ic_navigation_chevron_right"-->
<!--android:title="#string/about" />-->
<item
android:id="#+id/termsOfService"
android:icon="#drawable/ic_navigation_chevron_right"
android:title="#string/terms_of_service" />
<item
android:id="#+id/logout"
android:icon="#drawable/ic_navigation_chevron_right"
android:title="#string/log_out" />
</group>
Related
I have an Activity that uses a NavigationView to display my app menu.
When menu opens and closes my App bar change from the drawer icon to the back arrow as expected.
I have a scenario, where i click on item 1 from my app menu, and it opens a fragment in my FrameLayout, and then i need to click a button that opens another fragment, replacing the previous one.
The app bar has the drawer icon in the 2 fragments, and i want to have a back arrow on the second fragment, so i can return to first fragment
Here is my MainActivity
public class MainActivity extends SuperActivity {
#BindView(R.id.nav_view) NavigationView navigationView;
#BindView(R.id.drawer_layout) DrawerLayout drawerLayout;
#BindView(R.id.container) FrameLayout frameLayout;
#BindView(R.id.toolbar) Toolbar toolbar;
ActionBarDrawerToggle drawerToggle;
SuperFragment nextFragment;
FragmentManager fragmentManager;
String activeName;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ButterKnife.bind(this);
fragmentManager = getSupportFragmentManager();
setupView();
if (savedInstanceState == null) showHome();
}
private void setupView() {
setSupportActionBar(toolbar);
drawerLayout.setDrawerShadow(R.drawable.drawer_shadow, GravityCompat.START);
drawerToggle = new ActionBarDrawerToggle(this, drawerLayout, toolbar, R.string.drawer_open, R.string.drawer_close);
drawerLayout.addDrawerListener(drawerToggle);
drawerLayout.setScrimColor(Color.TRANSPARENT);
if (navigationView != null) {
setupDrawerContent(navigationView);
}
setupDrawerContent(navigationView);
navigationView.setNavigationItemSelectedListener(new NavigationView.OnNavigationItemSelectedListener() {
#Override
public boolean onNavigationItemSelected(#NonNull MenuItem item) {
drawerLayout.closeDrawer(Gravity.LEFT);
activeName = item.getTitle().toString();
toolbar.setTitle(activeName);
selectDrawerItem(item);
return false;
}
});
}
private void setupDrawerContent(NavigationView navigationView) {
navigationView.setNavigationItemSelectedListener(
new NavigationView.OnNavigationItemSelectedListener() {
#Override
public boolean onNavigationItemSelected(MenuItem menuItem) {
menuItem.setChecked(true);
drawerLayout.closeDrawers();
return true;
}
});
}
private void showHome() {
selectDrawerItem(navigationView.getMenu().getItem(0));
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home:
this.finish();
return true;
default:
return false;
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
return false;
}
private void selectDrawerItem(MenuItem menuItem) {
drawerLayout.closeDrawer(Gravity.LEFT);
switch (menuItem.getItemId()) {...}
}
#Override
protected void onPostCreate(Bundle savedInstanceState) {
drawerToggle.syncState();
super.onPostCreate(savedInstanceState);
}
#Override
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
drawerToggle.onConfigurationChanged(newConfig);
}
private Runnable Logout_Callback = new Runnable() {
public void run() {
Toast.makeText(getApplication(),"Log out",Toast.LENGTH_SHORT).show();
}
};
#Override
public boolean onSupportNavigateUp() {
onBackPressed();
return true;
}
}
that extends from this
public class SuperActivity extends AppCompatActivity implements InterfaceHostActivity{
private SuperFragment selectedFragment;
// Navigation adapter
public NavigationListAdapter mNavigationAdapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
public void replaceFragment(SuperFragment fragment, boolean addToBackStack) {
replaceFragment(fragment, addToBackStack, R.id.container);
}
public void replaceFragment(SuperFragment fragment, boolean addToBackStack, int layout) {
try {
FragmentManager manager = getSupportFragmentManager();
if (fragment.isMainFragment) {
manager.popBackStack(null, FragmentManager.POP_BACK_STACK_INCLUSIVE);
}
String backStateName = ((Object) fragment).getClass().getName();
boolean fragmentPopped = manager.popBackStackImmediate(backStateName, 0);
if (!fragmentPopped) {
FragmentTransaction ft = manager.beginTransaction();
ft.replace(layout, fragment, backStateName);
ft.setTransition(FragmentTransaction.TRANSIT_NONE);
if (addToBackStack)
ft.addToBackStack(backStateName);
ft.commit();
}
getSupportFragmentManager().executePendingTransactions();
} catch (Exception e) {
LogManager.logException(e);
}
}
#Override
public void setSelectedFragment(SuperFragment fragment) {
this.selectedFragment = fragment;
}
#Override
public void popBackStack() {
getSupportFragmentManager().popBackStackImmediate();
}
#Override
public void popBackStackUntilTag(String tag) {
getSupportFragmentManager().popBackStackImmediate(tag, FragmentManager.POP_BACK_STACK_INCLUSIVE);
}
#Override
public void addFragment(SuperFragment fragment, boolean addToBackStack) {
try {
String backStateName = ((Object) fragment).getClass().getName();
String fragmentTag = backStateName;
FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
ft.replace(R.id.container, fragment, fragmentTag);
ft.setTransition(FragmentTransaction.TRANSIT_NONE);
if (addToBackStack)
ft.addToBackStack(backStateName);
ft.commit();
} catch (Exception e) {
LogManager.logException(e);
}
}
#Override
public void addMultipleFragments(SuperFragment[] fragments) {
}
#Override
public void onBackPressed() {
boolean eventConsumed = false;
if (selectedFragment != null) {
eventConsumed = eventConsumed || selectedFragment.onBackPressed();
}
if (!eventConsumed) {
super.onBackPressed();
}
}
#Override
protected void onStart() {
super.onStart();
}
#Override
protected void onStop() {
super.onStop();
}
}
and my XML
<android.support.v4.widget.DrawerLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/drawer_layout"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="pt.sibs.android.mpos.activities.MainActivity">
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="match_parent">
<FrameLayout
android:id="#+id/container"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_marginTop="?attr/actionBarSize" />
<include layout="#layout/toolbar" />
</RelativeLayout>
<android.support.design.widget.NavigationView
android:id="#+id/nav_view"
android:layout_height="match_parent"
android:layout_width="wrap_content"
android:layout_gravity="start"
android:fitsSystemWindows="true"
app:customTypeface="#string/font_lato_light"
android:background="#color/menuBG"
android:layout_marginTop="?attr/actionBarSize"
app:itemTextColor="#color/drawer_text_color_selector"
app:itemTextAppearance="#style/TextViewBody"
app:itemIconTint="#color/menu_icon_selector"
app:itemBackground="#drawable/menu_item_bg"
app:menu="#menu/drawer_view"/>
</android.support.v4.widget.DrawerLayout>
when i am opening navigation drawer by clicking hamburger icon present in toolbar it opens it but when i click the left arrow to close the navigation drawer nothing is happening it is not closing it .please help
here is my code
public class MainActivity extends AppCompatActivity {
Toolbar toolbar;
NavigationDrawerFragment navigationDrawerFragment;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main_drawer);
toolbar=(Toolbar)findViewById(R.id.app_bar);
//findViewById(R.id.drawerlayout);
setSupportActionBar(toolbar);
navigationDrawerFragment= (NavigationDrawerFragment)
getSupportFragmentManager().findFragmentById(R.id.nav_frag);
navigationDrawerFragment.setup(R.id.nav_frag,(DrawerLayout) findViewById(R.id.drawerlayout),(Toolbar)findViewById(R.id.app_bar));
getSupportActionBar().setDisplayShowHomeEnabled(true);
final ActionBar actionBar = getSupportActionBar();
actionBar.setDisplayHomeAsUpEnabled(true);
/* if(actionBar!=null)
{
actionBar.setHomeAsUpIndicator(android.R.drawable.ic_dialog_dialer);
actionBar.setDisplayHomeAsUpEnabled(true);
}*/
}
#Override
public void onBackPressed() {
super.onBackPressed();
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.cool_menu,menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
int id= item.getItemId();
if(id==android.R.id.home)
{ ((DrawerLayout)findViewById(R.id.drawerlayout)).openDrawer(GravityCompat.START); // OPEN DRAWER
return true;
}
if(id==R.id.action_settings){
Toast.makeText(this, "this is setting", Toast.LENGTH_SHORT).show();
}
if(id==R.id.action_mail){
startActivity(new Intent(this,SubActivity.class));
}
if(id==R.id.action_help){
Toast.makeText(this, "this is action_help", Toast.LENGTH_SHORT).show();
}
return true;
}
}
activity_main_drawer.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<include
android:id="#+id/app_bar"
layout="#layout/app_bar"></include>
<android.support.v4.widget.DrawerLayout
android:id="#+id/drawerlayout"
android:layout_width="match_parent"
android:layout_height="match_parent">
android:layout_width="match_parent"
android:layout_height="match_parent">
<fragment
android:id="#+id/nav_frag"
android:name="com.example.adarsh.material.NavigationDrawerFragment"
android:layout_width="280dp"
android:layout_height="match_parent"
android:layout_gravity="start"
tools:layout="#layout/fragment_navigation_drawer" />
</android.support.v4.widget.DrawerLayout>
NavigationDrawerFragment.java
public class NavigationDrawerFragment extends Fragment {
private static final String FILE_NAME = "shared";
private static final String SHARED_KEY ="shared_key" ;
private DrawerLayout mDrawerLayout;
private View containerView;
private ActionBarDrawerToggle mDrawerToggle;
private boolean mUserLearnerDrawer;
private boolean mFromSaveInstances;
public NavigationDrawerFragment() {
// Required empty public constructor
}
#Override
public void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState); mUserLearnerDrawer=Boolean.valueOf(readFromSharedPreferences(getActivity(),SHARED_KEY,"false"));
if(savedInstanceState!=null){
mFromSaveInstances=true;
}
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
return inflater.inflate(R.layout.fragment_navigation_drawer, container, false);
}
public void setup(int id,DrawerLayout drawerLayout, Toolbar toolbar) {
containerView=getActivity().findViewById(id);
mDrawerLayout=drawerLayout;
mDrawerToggle=new ActionBarDrawerToggle(getActivity(),drawerLayout,R.string.open,R.string.close){
#Override
public void onDrawerOpened(View drawerView) {
super.onDrawerOpened(drawerView);
//we are going to store the mUserLearnerDrawer in shared pref
//if it is saved then we will not show the drawer then we will show the drawer
//if the user has never seeen the drawer before
if(!mUserLearnerDrawer){
mUserLearnerDrawer=true;
saveToSharedPreferences(getActivity(),SHARED_KEY,mUserLearnerDrawer+"");
}
getActivity().invalidateOptionsMenu();// it going to make draw the action bar again
}
#Override
public void onDrawerClosed(View drawerView) {
super.onDrawerClosed(drawerView);
getActivity().invalidateOptionsMenu();
}
};
//never seen the drawer + never used it before
if(!mUserLearnerDrawer&&!mFromSaveInstances){
mDrawerLayout.openDrawer(containerView);
}
mDrawerLayout.addDrawerListener(mDrawerToggle);
mDrawerLayout.post(new Runnable() {
#Override
public void run() {
mDrawerToggle.syncState();
}
});
}
public void saveToSharedPreferences(Context context,String name,String value){
SharedPreferences sPrefs=context.getSharedPreferences(FILE_NAME,Context.MODE_PRIVATE);
SharedPreferences.Editor editor=sPrefs.edit();
editor.putString(name,value);
editor.apply();//apply is faster then the commit method .coz unlike commit it does not return that yes it is commited or not
}
public String readFromSharedPreferences(Context context,String name,String defaultValue){
SharedPreferences sPrefs=context.getSharedPreferences(FILE_NAME,Context.MODE_PRIVATE);
return sPrefs.getString(name,defaultValue);
}
}
create a global variable
private boolean isDrawerOpen = false;
then in your onOptionItemSelected do something like this
#Override
public boolean onOptionsItemSelected(MenuItem item) {
int id= item.getItemId();
if(id==android.R.id.home)
{
DrawerLayout drawerLayout = (DrawerLayout)findViewById(R.id.drawerlayout);
if(isDrawerOpen){
isDrawerOpen = false;
drawaerLayout.closeDrawer(GravityCompat.START);
} else{
isDrawerOpen = true;
drawaerLayout.openDrawer(GravityCompat.START);
}
return true;
}
if(id==R.id.action_settings){
Toast.makeText(this, "this is setting", Toast.LENGTH_SHORT).show();
}
if(id==R.id.action_mail){
startActivity(new Intent(this,SubActivity.class));
}
if(id==R.id.action_help){
Toast.makeText(this, "this is action_help", Toast.LENGTH_SHORT).show();
}
return true;
}
I am developing an Android app about music. In this app, I have two fragments: PopFragment e GenresFragment.
In the XML file of PopFragment called fragment_pop.xml, I have toolbar with a back arrow that goes back to GenresFragment.
My toolbar code is this:
<android.support.design.widget.AppBarLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:theme="#style/ThemeOverlay.AppCompat.Dark.ActionBar"
>
<include
android:layout_height="wrap_content"
android:layout_width="match_parent"
layout="#layout/toolbar_layout"
/>
</android.support.design.widget.AppBarLayout>
<ImageButton
android:id="#+id/arrowPop"
android:layout_width="54dp"
android:layout_height="wrap_content"
android:src="#drawable/ic_arrow_back_black_24dp"
style="?android:attr/borderlessButtonStyle"
/>
In the Java file of PopFragment called PopActivity, I have some code but it's not working.
I have this code:
public class PopActivity extends AppCompatActivity implements View.OnClickListener {
public PopActivity() {
// Required empty public constructor
}
#Override
protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.fragment_pop);
Toolbar toolbar = (Toolbar)findViewById(R.id.toolBar);
setSupportActionBar(toolbar);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setDisplayShowHomeEnabled(true);
ImageButton backBtn = (ImageButton)findViewById(R.id.arrowPop);
}
#Override
public void onClick (View view) {
Intent i = new Intent();
switch (view.getId()) {
case R.id.arrowPop:
break;
}
}
Can you help me please?
Thank you
Try something like:
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater){
inflater.inflate(R.menu.your_menu, menu);
}
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home: {
getActivity().onBackPressed();
break;
}
}
return true;
}
You generally don't need to add your own arrow icon, the Toolbar should be able to handle it for you.
if(shouldShowArrow()) {
drawerLayout.setDrawerLockMode(LOCK_MODE_LOCKED_CLOSED, GravityCompat.START);
drawerToggle.setDrawerIndicatorEnabled(false);
MyActivity.this.getSupportActionBar().setDisplayHomeAsUpEnabled(true);
} else { // hamburglar icon
drawerLayout.setDrawerLockMode(LOCK_MODE_UNLOCKED, GravityCompat.START);
MyActivity.this.getSupportActionBar().setDisplayHomeAsUpEnabled(false);
drawerToggle.setDrawerIndicatorEnabled(true);
}
drawerToggle.syncState();
And then you can define what happens when you click the arrow
#Override
protected void onCreate(Bundle bundle) {
super.onCreate(bundle);
ButterKnife.bind(this);
setSupportActionBar(toolbar);
ActionBar actionBar = getSupportActionBar();
drawerToggle = new ActionBarDrawerToggle(MyActivity.this, drawerLayout, toolbar, R.string.open, R.string.close) {
#Override
public void onDrawerClosed(View drawerView) {
super.onDrawerClosed(drawerView);
MyActivity.this.supportInvalidateOptionsMenu();
}
#Override
public void onDrawerOpened(View drawerView) {
super.onDrawerOpened(drawerView);
MyActivity.this.supportInvalidateOptionsMenu();
}
};
drawerLayout.setDrawerListener(drawerToggle);
drawerToggle.setToolbarNavigationClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// what to do when you click the arrow
}
});
actionBar.setDisplayHomeAsUpEnabled(false);
actionBar.setHomeButtonEnabled(true);
}
#Override
protected void onPostCreate(Bundle bundle) {
super.onPostCreate(bundle);
drawerToggle.syncState();
}
#Override
protected void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
drawerToggle.onConfigurationChanged(newConfig);
}
Use the following code as a quick fix, which mimics the back button being pressed.
switch (view.getId()) {
case R.id.arrowPop:
onBackPressed();
break;
}
Using this code, you shouldn't have to define the back button in the toolbar yourself, Android will handle it.
Toolbar toolbar = (Toolbar) findViewById(R.id.my_awesome_toolbar);
setSupportActionBar(toolbar);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setDisplayShowHomeEnabled(true);
Then when you click the back button, Android will call onBackPressed() for you.
I've a single activity(MainActivity) which extends actionbaractivity and implements NavigationDrawer. I've setup the drawertoggle in the activity itself.
I'm creating new fragments from a fragment that was created by another fragment which is in turn created by the MainActivity. ( MainActivity -> HomeFragment ->AnotherFragment).
MainActivity.java
public class MainActivity extends ActionBarActivity implements FragmentDrawer.FragmentDrawerListener, TitleSetter, NavigationDrawerEnabler{
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
myToolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(myToolbar);
getSupportActionBar().setHomeButtonEnabled(true);
//getSupportActionBar().setDisplayHomeAsUpEnabled(true);
drawerFragment = (FragmentDrawer)
getSupportFragmentManager().findFragmentById(R.id.fragment_navigation_drawer);
setUp(R.id.fragment_navigation_drawer, (DrawerLayout) findViewById(R.id.drawer_layout), myToolbar);
mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
drawerFragment.setDrawerListener(this);
// display the first navigation drawer view on app launch
displayView(0);
}
#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 super.OncreateOptionsMenu(menu);
}
#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.
/* This function is never called even if the Up caret button is pressed!! */
if (mDrawerToggle.isDrawerIndicatorEnabled() &&
mDrawerToggle.onOptionsItemSelected(item))
return true;
switch (item.getItemId()) {
case android.R.id.home:
/*This case doesn't occur*/
return true;
case R.id.action_settings:
return true;
default:
return super.onOptionsItemSelected(item);
}
}
#Override
public void onDrawerItemSelected(View view, int position) {
mDrawerLayout.closeDrawer(containerView);
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);
break;
case 1:
fragment = new SomeFragment();
title = getString(R.string.title_something);
break;
case 2:
//fragment = new SomeotherFragment();
//title = getString(R.string.title_somethings);
break;
default:
break;
}
if (fragment != null) {
FragmentManager fragmentManager = getSupportFragmentManager();
FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
fragmentTransaction.replace(R.id.container_body, fragment);
fragmentTransaction.commit();
getSupportActionBar().setTitle(title);
}
}
#Override
public void setTitle(String title) {
getSupportActionBar().setTitle(title);
}
public void setUp(int fragmentId, DrawerLayout drawerLayout, final Toolbar toolbar) {
containerView = findViewById(fragmentId);
mDrawerLayout = drawerLayout;
mDrawerToggle = new ActionBarDrawerToggle(this, drawerLayout, toolbar, R.string.drawer_open, R.string.drawer_close) {
#Override
public void onDrawerOpened(View drawerView) {
super.onDrawerOpened(drawerView);
getSupportActionBar().invalidateOptionsMenu();
}
#Override
public void onDrawerClosed(View drawerView) {
super.onDrawerClosed(drawerView);
getSupportActionBar().invalidateOptionsMenu();
}
#Override
public void onDrawerSlide(View drawerView, float slideOffset) {
super.onDrawerSlide(drawerView, slideOffset);
toolbar.setAlpha(1 - slideOffset / 2);
}
};
mDrawerLayout.setDrawerListener(mDrawerToggle);
mDrawerLayout.post(new Runnable() {
#Override
public void run() {
mDrawerToggle.syncState();
}
});
}
#Override
public void onBackPressed() {
super.onBackPressed();
enableNavigationDrawer(true);
}
#Override
public void enableNavigationDrawer(boolean isEnabled) {
if ( isEnabled ) {
mDrawerLayout.setDrawerLockMode(DrawerLayout.LOCK_MODE_UNLOCKED);
getSupportActionBar().setDisplayHomeAsUpEnabled(false);
mDrawerToggle.setDrawerIndicatorEnabled(true);
mDrawerToggle.syncState();
}
else {
mDrawerLayout.setDrawerLockMode(DrawerLayout.LOCK_MODE_LOCKED_CLOSED);
mDrawerToggle.setDrawerIndicatorEnabled(false);
getSupportActionBar().setDisplayShowHomeEnabled(true);
getSupportActionBar().setHomeButtonEnabled(true);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
mDrawerToggle.syncState();
}
}
}
HomeFragment.java
public class HomeFragment extends Fragment implements View.OnClickListener {
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.home, container, false);
// Inflate the layout for this fragment
fab = (FloatingActionButton) rootView.findViewById(R.id.fab);
fab.setOnClickListener(this);
((TitleSetter) getActivity()).setTitle("Home");
return rootView;
}
#Override
public void onAttach(Activity activity) {
super.onAttach(activity);
}
#Override
public void onDetach() {
super.onDetach();
}
#Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.fab:
((NavigationDrawerEnabler) getActivity()).enableNavigationDrawer(false);
Fragment newFragment = new NewWord();
FragmentManager fragmentManager = getFragmentManager();
FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
fragmentTransaction.replace(R.id.container_body, newFragment);
fragmentTransaction.addToBackStack(null);
// Commit the transaction
fragmentTransaction.commit();
break;
}
}
}
AnotherFragment.java
public class NewWord extends Fragment {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setHasOptionsMenu(true);
}
#Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
super.onCreateOptionsMenu(menu, inflater);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Get item selected and deal with it
/*Not even this*/
Log.d("KEY: ", String.valueOf(item.getItemId()));
switch (item.getItemId()) {
case android.R.id.home:
/* Doesn't execute*/
Log.d("Fragment", "I'm here");
getActivity().onBackPressed();
return true;
default:
return super.onOptionsItemSelected(item);
}
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.new_word, container, false);
return rootView;
}
#Override
public void onAttach(Activity activity) {
super.onAttach(activity);
((TitleSetter) activity).setTitle("Text");
}
Also the drawer layout
<android.support.v4.widget.DrawerLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/drawer_layout"
android:layout_width="match_parent"
android:layout_height="match_parent">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<LinearLayout
android:id="#+id/container_toolbar"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical">
<include
android:id="#+id/toolbar"
layout="#layout/toolbar" />
</LinearLayout>
<FrameLayout
android:id="#+id/container_body"
android:layout_width="fill_parent"
android:layout_height="0dp"
android:layout_weight="1" >
</FrameLayout>
</LinearLayout>
<fragment
android:id="#+id/fragment_navigation_drawer"
android:name="com.calgen.wordbook.activity.FragmentDrawer"
android:layout_width="#dimen/nav_drawer_width"
android:layout_height="match_parent"
android:layout_gravity="start"
app:layout="#layout/fragment_nav_drawer"
tools:layout="#layout/fragment_nav_drawer" />
And menu_main.xml
<menu 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"
tools:context=".MainActivity">
<item
android:id="#+id/action_search"
android:title="#string/action_search"
android:orderInCategory="100"
android:icon="#drawable/ic_action_search"
app:showAsAction="ifRoom" />
<item
android:id="#+id/action_settings"
android:title="#string/action_settings"
android:orderInCategory="100"
app:showAsAction="never" />
I actually referred this tutorial to setup navigation drawer fragment : Android Hive.
I also referred similar questions answered here on stackoverflow :
1.Switching between Android Navigation Drawer image and Up caret when using fragments
2.My problem is similiar to this : Android Navigation Drawer Show Up Indicator for Lower Level Fragments.
- I couldn't comment here as i do not have 50 reps. I implemented what was exactly told in the comments.
But still clicking on the up caret doesn't run the function onOptionItemSelected, even though i've homebutton enabled.!
I'm now adding my custom styles.xml, may be some error in this?
<?xml version="1.0" encoding="utf-8"?>
<resources>
<style name="MyMaterialTheme" parent="MyMaterialTheme.Base"></style>
<style name="MyMaterialTheme.Base" parent="Theme.AppCompat">
<item name="windowNoTitle">true</item>
<item name="windowActionBar">false</item>
<item name="android:activatedBackgroundIndicator">#drawable/nav_background</item>
<item name="colorPrimary">#color/colorPrimary</item>
<item name="colorPrimaryDark">#color/colorPrimaryDark</item>
<item name="android:textColorPrimary">#color/textColorPrimary</item>
<item name="colorAccent">#color/colorAccent</item>
</style>
</resources>
Also the custom toolbar.xml
<?xml version="1.0" encoding="utf-8"?>
<android.support.v7.widget.Toolbar
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:local="http://schemas.android.com/apk/res-auto"
android:id="#+id/toolbar"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:minHeight="?attr/actionBarSize"
android:background="?attr/colorPrimary"
local:theme="#style/ThemeOverlay.AppCompat.Dark.ActionBar"
local:popupTheme="#style/ThemeOverlay.AppCompat.Light" />
SOLVED FINALLY
I figured out the problem, it is due to the custom toolbar that I used. When a custom toolbar is set up, we also have to set a listener on the up caret using the method called drawertoggler.setNaviagtionOnClickListener
In the onCreate() method of the activity we need to add the following code:
drawertoggler.setToolbarNavigationClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
getSupportFragmentManager().popBackStackImmediate();
}
});
Other cases like OnBackPressed can be handled by setting a OnStackChangeListener in the activity and make necessary changes. It is clearly explained here :#riwnodennyk.
I'm trying to use NavigationDrawer on my activity (Home), but the content of activity is not shown.
home_activity.xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:id="#+id/home_activity">
<Button
android:id="#+id/like_count"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:onClick="likeCounter"
android:background="#drawable/likecountgreen" />
</LinearLayout>
activity_drawer.xml
<android.support.v4.widget.DrawerLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/drawer_layout"
android:layout_width="match_parent"
android:layout_height="match_parent" >
<FrameLayout
android:id="#+id/content_frame"
android:layout_width="match_parent"
android:layout_height="match_parent">
</FrameLayout>
<ListView
android:id="#+id/nav_drawer"
android:layout_width="240dp"
android:layout_height="match_parent"
android:layout_gravity="start"
android:background="#fff"
android:choiceMode="singleChoice" />
HomeActivity.class
public class HomeActivity extends BaseActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.home_activity);
super.onCreateDrawer();
}
}
BaseActivity.class
public class BaseActivity extends ActionBarActivity implements AdapterView.OnItemClickListener {
private ListView drawerList;
private DrawerLayout drawerLayout;
private ActionBarDrawerToggle mDrawerToggle;
private String[] options;
private TextView titleActionBar;
protected void onCreateDrawer() {
setContentView(R.layout.activity_drawer);
setupActionBar();
options = getResources()
.getStringArray(R.array.drawer_options);
drawerLayout =
(DrawerLayout) findViewById(R.id.drawer_layout);
drawerList = (ListView) findViewById(R.id.nav_drawer);
drawerList.setAdapter(new ArrayAdapter<String>(this,
android.R.layout.simple_list_item_1, options));
drawerList.setOnItemClickListener(this);
setupDrawer();
}
private void setupActionBar() {
getSupportActionBar().setDisplayOptions(ActionBar.DISPLAY_SHOW_CUSTOM);
getSupportActionBar().setCustomView(R.layout.action_bar);
titleActionBar = (TextView) findViewById(R.id.title_action_bar);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setHomeButtonEnabled(true);
}
private void setupDrawer() {
mDrawerToggle = new ActionBarDrawerToggle(this, drawerLayout, R.string.drawer_open, R.string.drawer_close) {
public void onDrawerClosed(View view) {
super.onDrawerClosed(view);
titleActionBar.setText("App");
invalidateOptionsMenu();
}
public void onDrawerOpened(View drawerView) {
super.onDrawerOpened(drawerView);
titleActionBar.setText("Options");
invalidateOptionsMenu();
}
};
mDrawerToggle.setDrawerIndicatorEnabled(true);
drawerLayout.setDrawerListener(mDrawerToggle);
}
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
switch (position) {
case 2:
startActivity(new Intent(getApplicationContext(), LoginActivity.class));
overridePendingTransition(R.anim.abc_fade_in, R.anim.abc_fade_out);
drawerLayout.closeDrawer(drawerList);
break;
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.home_menu, menu);
return super.onCreateOptionsMenu(menu);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
if (id == R.id.action_search) {
return true;
}
if (mDrawerToggle.onOptionsItemSelected(item)) {
return true;
}
return super.onOptionsItemSelected(item);
}
#Override
protected void onPostCreate(Bundle savedInstanceState) {
super.onPostCreate(savedInstanceState);
mDrawerToggle.syncState();
}
#Override
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
mDrawerToggle.onConfigurationChanged(newConfig);
}
}
What I've discovered is that drawer_activity is overlaying home_activity.
How can I solve it?
In onCreateDrawer you are setting a new layout, so your layout that you set in your MainActivity is not shown anymore. Here is how you can solve this:
HomeActivity:
public class HomeActivity extends BaseActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
super.onCreateDrawer(R.layout.home_activity);
}
}
And in your BaseActivity:
protected FrameLayout content;
protected void onCreateDrawer(final int layoutResID) {
setContentView(R.layout.activity_drawer);
content = (FrameLayout) findViewById(R.id.content_frame);
getLayoutInflater().inflate(layoutResID, content, true);
setupActionBar();
options = getResources()
.getStringArray(R.array.drawer_options);
drawerLayout =
(DrawerLayout) findViewById(R.id.drawer_layout);
drawerList = (ListView) findViewById(R.id.nav_drawer);
drawerList.setAdapter(new ArrayAdapter<String>(this,
android.R.layout.simple_list_item_1, options));
drawerList.setOnItemClickListener(this);
setupDrawer();
}
Now the FrameLayout in your activity_drawer layout contains the layout of your HomeActivity.