How to handle back arrow click? - android

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.

Related

Hamburger icon changes on Back Arrow icon after closing the previous Activity

I am opening an About page from the Navigation drawer of an application. It creates an intent and starts a new Activity. In the AboutActivity I show a Back Arrow and when I close this activity on my MainActivity the Hamburger icon changes to Back Arrow icon.
Here is MainActivity:
#Override
protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mDrawerToggle = new ActionBarDrawerToggle(
this, mDrawer, mToolbar, R.string.drawer_open, R.string.drawer_close) {
#Override
public void onDrawerOpened(View drawerView) {
super.onDrawerOpened(drawerView);
LogUtils.d(TAG, "onDrawerOpened() ");
KeyboardUtils.hideKeyboard(getBaseContext(), drawerView);
invalidateOptionsMenu();
}
#Override
public void onDrawerClosed(View drawerView) {
super.onDrawerClosed(drawerView);
LogUtils.d(TAG, "onDrawerClosed: " + getTitle());
invalidateOptionsMenu();
}
};
//calling sync state is necessary or else your hamburger icon wont show up
mDrawerToggle.setDrawerIndicatorEnabled(true);
mDrawerToggle.syncState();
/* res/menu/drawer_menu.xml */
mNavigationView.setNavigationItemSelectedListener(this);
setContentView(R.layout.activity_main);
}
#Override
protected void onResume() {
super.onResume();
if(getSupportActionBar() != null){
getSupportActionBar().setDisplayHomeAsUpEnabled(false);
}
mDrawerToggle.syncState();
}
Here is About activity:
public class AboutActivity extends AppCompatActivity {
#Override
protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
final String version = getString(R.string.about_version, BuildConfig.VERSION_NAME, String.valueOf(BuildConfig.VERSION_CODE));
final View aboutPage = new AboutPage(this)
.isRTL(false)
.setDescription(version)
.addGroup("Connect with us")
.addEmail("log#lunni.fi")
.addPlayStore("fi.lunni.mobileadvisor")
.addYoutube("UCubK_NmfkAGPzo5UfiStsVQ")
.addWebsite("https://lunni.fi/")
.create();
final ImageView image = (ImageView) aboutPage.findViewById(mehdi.sakout.aboutpage.R.id.image);
image.setImageDrawable(ImgUtils.changeColor(this, R.drawable.lunni_logo_icon_white, R.color.lunni_blue));
setContentView(aboutPage);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
// Respond to the action bar's Up/Home button
case android.R.id.home:
NavUtils.navigateUpFromSameTask(this);
return true;
}
return super.onOptionsItemSelected(item);
}
}
And in the Manifest.xml
<activity android:name=".ui.activities.AboutActivity">
<meta-data
android:name="android.support.PARENT_ACTIVITY"
android:value=".ui.activities.MainActivity" />
</activity>
Remove this line from onResume():
getSupportActionBar().setDisplayHomeAsUpEnabled(false);

Navigation Drawer Not Properly Opening

I added a navigation drawer to my toolbar and added the toolbar to my HomePage Activity. The Drawer seems to be working fine but only pulls out when I slide my finger below the hamburger icon. Otherwise, if I simply click on the icon nothing happens. Does anybody know why? I watched the following tutorial and ideally when the hamburger icon is clicked, the drawer should come out: https://www.youtube.com/watch?v=Lfc1q1dFB3E
Is there an onClick attribute that I'm missing? Here is my code:
public class HomePage extends AppCompatActivity implements View.OnClickListener {
private DrawerLayout drawerLayout;
private ListView drawerList;
private ActionBarDrawerToggle drawerToggle;
String[] drawerListItems;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_home_page);
Toolbar myToolbar = (Toolbar) findViewById(R.id.toolBarHome);
drawerLayout = (DrawerLayout)findViewById(R.id.homePageDrawer);
drawerList = (ListView)findViewById(R.id.homePageList);
drawerListItems = getResources().getStringArray(R.array.activities);
drawerList.setAdapter(new ArrayAdapter<String>(this,android.R.layout.simple_list_item_1,drawerListItems));
drawerList.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
switch (position) {
case 0: {
Intent i = new Intent(HomePage.this, HomePage.class);
startActivity(i);
break;
}
case 1: {
Intent i = new Intent(HomePage.this, Allergy.class);
startActivity(i);
break;
}
}
drawerLayout.closeDrawer(drawerList);
}
});
drawerToggle = new ActionBarDrawerToggle(this,drawerLayout,myToolbar,R.string.drawer_open,R.string.drawer_close)
{
#Override
public void onDrawerOpened(View drawerView) {
super.onDrawerOpened(drawerView);
invalidateOptionsMenu();
syncState();
}
#Override
public void onDrawerClosed(View drawerView) {
super.onDrawerClosed(drawerView);
invalidateOptionsMenu();
syncState();
}
};
drawerLayout.setDrawerListener(drawerToggle);
setSupportActionBar(myToolbar);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setHomeButtonEnabled(true);
drawerToggle.syncState();
}
#Override
protected void onPostCreate(Bundle savedInstanceState) {
super.onPostCreate(savedInstanceState);
drawerToggle.syncState();
}
#Override
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
drawerToggle.onConfigurationChanged(newConfig);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()){
case R.id.home:{
if (drawerLayout.isDrawerOpen(drawerList)){
drawerLayout.closeDrawer(drawerList);
}else{
drawerLayout.openDrawer(drawerList);
}
return true;
}
default:return super.onOptionsItemSelected(item);
}
}
Here is the XML layout. I have one ImageView on my Homepage Activity. When the NavigationDrawer pulls out, I need it to cover the existing ImageView, so I placed it within a relative layout within my drawerlayout:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:background="#drawable/boardlayered"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
<android.support.v7.widget.Toolbar
android:id="#+id/toolBarHome"
android:layout_width="match_parent"
android:layout_height="?attr/actionBarSize"
android:background="?attr/colorPrimary">
</android.support.v7.widget.Toolbar>
<android.support.v4.widget.DrawerLayout
android:id="#+id/homePageDrawer"
android:layout_below="#+id/toolBarHome"
android:layout_width="match_parent"
android:layout_height="match_parent">
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="match_parent">
<ImageView
android:id="#+id/dogPic"
android:background="#drawable/happy_dog"
android:layout_width="175dp"
android:layout_height="200dp"
android:layout_alignParentBottom="true"
android:layout_marginLeft="20dp" />
</RelativeLayout>
<ListView
android:id="#+id/homePageList"
android:background="#android:color/white"
android:layout_gravity="start"
android:layout_width="305dp"
android:layout_height="match_parent"></ListView>
</android.support.v4.widget.DrawerLayout>
Found it. The issue is in this piece of code, which is directly responsible for the hamburger icon to perform an action:
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()){
case R.id.home:{
if (drawerLayout.isDrawerOpen(drawerList)){
drawerLayout.closeDrawer(drawerList);
}else{
drawerLayout.openDrawer(drawerList);
}
return true;
}
default:return super.onOptionsItemSelected(item);
}}
Specifically
case R.id.home:
Should be
case android.R.id.home:
This latter case syntax is what works
I think the problem here is with the lines:
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setHomeButtonEnabled(true);
It seems this will try to use your toggle button as an 'up' navigation button instead, if you're trying to use the hamburger button to open and close your drawer you can remove these lines.

Changing Navigation drawer hamburger icon

I am trying to change hamburger menu icon for NavigationView but I am unable to do so.
Here is what I have tried so far
I have a base activity where nav drawer setup is done. Here is relevant piece of code
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
super.setContentView(R.layout.activity_base_nav);
setSupportActionBar(toolbar);
setupDrawer();
}
private void setupDrawer() {
mDrawerLayout.setDrawerListener(this);
mDrawerToggle = new ActionBarDrawerToggle(this,
mDrawerLayout,
R.string.open,
R.string.close);
mDrawerToggle = new ActionBarDrawerToggle(mContext,
mDrawerLayout,
R.string.open,
R.string.close);
mDrawerLayout.setDrawerListener(mDrawerToggle);
if (getSupportActionBar() != null) {
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setDefaultDisplayHomeAsUpEnabled(false);
mDrawerToggle.setDrawerIndicatorEnabled(false);
mDrawerToggle.setHomeAsUpIndicator(R.drawable.ic_share_48pt_2x);
}
mDrawerToggle.syncState();
mNavigationView.setNavigationItemSelectedListener(
menuItem -> {
mMenuItem = menuItem.getItemId();
mDrawerUtil.onNavMenuItemClicked(mMenuItem);
mDrawerLayout.closeDrawers();
return true;
});
}
#Override
public void setContentView(int layoutResID) {
getLayoutInflater().inflate(layoutResID, mContainer);
}
#Override
protected void onPostCreate(Bundle savedInstanceState) {
super.onPostCreate(savedInstanceState);
mDrawerToggle.syncState();
}
#Override
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
mDrawerToggle.onConfigurationChanged(newConfig);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
if (mDrawerToggle.onOptionsItemSelected(item)) {
return true;
}
return super.onOptionsItemSelected(item);
}
However it doesn't seem to be working for me. I have also tried calling setDrawerIndicatorEnabled(false) and setHomeAsUpIndicator(R.drawable.ic_share_48pt_2x) on SupportActionBar but that also doesn't work.
The following code works nicely for me,
protected void onCreate(Bundle savedInstanceState) {
...
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setDefaultDisplayHomeAsUpEnabled(false);
toggle.setDrawerIndicatorEnabled(false);
toggle.setHomeAsUpIndicator(R.drawable.ic_custom_drawer_icon);
...
}
I also had to add a toolbar navigation click listener to listen for click events on the custom drawer icon
protected void onCreate(Bundle savedInstanceState) {
...
toggle.setToolbarNavigationClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
if (drawer.isDrawerOpen(GravityCompat.START)) {
drawer.closeDrawer(GravityCompat.START);
} else {
drawer.openDrawer(GravityCompat.START);
}
}
});
...
}
Finally, I can update the icon dynamically as
toggle.setHomeAsUpIndicator(R.drawable.ic_new_icon);
Just use this :
toolbar.post(new Runnable() {
#Override
public void run() {
Drawable d = ResourcesCompat.getDrawable(getResources(), R.mipmap.ic_launcher, null);
toolbar.setNavigationIcon(d);
}
});
You dont need to handle setToolbarNavigationClickListener which is in accepted answer.
Here's what works for me:
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
setSupportActionBar(toolbar)
val toggle = ActionBarDrawerToggle(
this, drawer_layout, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close)
//toggle.isDrawerSlideAnimationEnabled = false
toggle.isDrawerIndicatorEnabled = false
toggle.setToolbarNavigationClickListener {
if (drawer_layout.isDrawerOpen(GravityCompat.START))
drawer_layout.closeDrawer(GravityCompat.START)
else
drawer_layout.openDrawer(GravityCompat.START)
}
toggle.setHomeAsUpIndicator(AppCompatResources.getDrawable(this, R.drawable.ic_android_black_24dp))
drawer_layout.addDrawerListener(toggle)
toggle.syncState()
nav_view.setNavigationItemSelectedListener(this)
}
override fun onBackPressed() {
if (drawer_layout.isDrawerOpen(GravityCompat.START)) {
drawer_layout.closeDrawer(GravityCompat.START)
} else {
super.onBackPressed()
}
}
override fun onNavigationItemSelected(item: MenuItem): Boolean {
when (item.itemId) {
...
}
drawer_layout.closeDrawer(GravityCompat.START)
return true
}
Have you try to look at the documentation ?
http://developer.android.com/training/implementing-navigation/nav-drawer.html
I've found this piece of code in it :
mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
mDrawerToggle = new ActionBarDrawerToggle(this, mDrawerLayout,
R.drawable.ic_drawer, R.string.drawer_open, R.string.drawer_close) {
/** Called when a drawer has settled in a completely closed state.*/
public void onDrawerClosed(View view) {
super.onDrawerClosed(view);
getActionBar().setTitle(mTitle);
invalidateOptionsMenu(); // creates call to onPrepareOptionsMenu()
}
/** Called when a drawer has settled in a completely open state. */
public void onDrawerOpened(View drawerView) {
super.onDrawerOpened(drawerView);
getActionBar().setTitle(mDrawerTitle);
invalidateOptionsMenu(); // creates call to onPrepareOptionsMenu()
}
};
With custom Toolbar
Set your Toolbar as ActionBar.
Then add homeicon using actionBar.setDisplayHomeAsUpEnabled(true);
Code snippet:
Toolbar toolbar = findViewById(R.id.customFBToolbar);
setSupportActionBar(toolbar);
ActionBar actionBar = getSupportActionBar();
actionBar.setDisplayHomeAsUpEnabled(true);
actionBar.setHomeAsUpIndicator(R.drawable.myham); // This is the line where you set the drawable
actionBar.setDisplayShowTitleEnabled(false);
Result:
Full code:
custom_toolbar.xml
<?xml version="1.0" encoding="utf-8"?>
<androidx.appcompat.widget.Toolbar
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:id="#+id/psyche_toolbar"
android:layout_width="match_parent"
android:layout_height="56sp"
android:background="#color/colorPrimaryDark"
android:elevation="4dp"
android:theme="#style/ThemeOverlay.AppCompat.Dark.ActionBar"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:popupTheme="#style/ThemeOverlay.AppCompat.Light"
tools:ignore="title"
tools:targetApi="lollipop">
<TextView
android:text="Facebook"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textColor="#ffffff"
android:layout_gravity="center"
android:textStyle="bold"
android:textSize="20sp"
/>
<ImageView
android:layout_width="35dp"
android:layout_height="35dp"
android:layout_gravity="end"
android:layout_marginEnd="20sp"
android:elevation="4dp"
android:src="#android:drawable/ic_dialog_email"/>
</androidx.appcompat.widget.Toolbar>
MainActivity.java
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = findViewById(R.id.customFBToolbar);
setSupportActionBar(toolbar);
ActionBar actionBar = getSupportActionBar();
actionBar.setDisplayHomeAsUpEnabled(true);
actionBar.setHomeAsUpIndicator(R.drawable.myham); // This is the line where you set the drawable
actionBar.setDisplayShowTitleEnabled(false);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home:
Toast.makeText(MainActivity.this, "Home button clicked", Toast.LENGTH_SHORT).show();
return true;
default:
return super.onOptionsItemSelected(item);
}
}
}
activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="#+id/drawer_layout">
<include layout="#layout/custom_toolbar"
android:id="#+id/customFBToolbar"
android:layout_alignParentTop="true"
android:layout_width="match_parent"
android:layout_height="wrap_content"
/>
</RelativeLayout>
You can use this method to set navigation with icons in the whole application, I am sure it will work for you.its simple method
mainActivity.java
getSupportActionBar().bar.setDisplayHomeAsUpEnabled(true);//Doing so will make the icon appear
navController.addOnDestinationChangedListener(new NavController.OnDestinationChangedListener() {
#Override
public void onDestinationChanged(#NonNull NavController navController, #NonNull NavDestination navDestination, #Nullable Bundle bundle) {
if ( mAppBarConfiguration.getTopLevelDestinations().contains(navDestination.getId())){
toolbar.setNavigationIcon(R.drawable.yout_drawer_icon);
} else {
toolbar.setNavigationIcon(R.drawable.you_back_icon);
}
}
});

The issue with toolbar and navigation View

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>

How to set navigation home button in android for appcompat activity for toolbar?

I am using the appcompat activity for Android v-21. I want to enable the home button which I have set it to true in my code. I also have overridden the onOptionsItemSelected but it's still not working.
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_apply_card);
mToolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(mToolbar);
//Action bar
getSupportActionBar().setHomeButtonEnabled(true);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
onBackPressed();
return true;
}
Simple way to add action bar home enable in Appcompat activity
getSupportActionBar().show();
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
Add this two pulic functions in your activity also--
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home:
// app icon in action bar clicked; go home
this.finish();
return true;
default:
return super.onOptionsItemSelected(item);
}
}
#Override
public void onBackPressed() {
// TODO Auto-generated method stub
super.onBackPressed();
}
Following code snippet set navigation icon in toolbar,
toolbar.setNavigationIcon(R.mipmap.ic_launcher);
I hope it will help you.
I know it is an old question but in order to prevent others to devote their time to solve this issue, I want to share the working method for me.
I am not sure about the reason of this. Probably, since ActionBar is deprecated and gave way to Toolbar after AppCompat, some methods of AppCompatActivity may not work as it is expected. Although the Burger (navigation button) is defined as the home button of ActionBar, we could not control click events of this button by using .onOptionsItemSelected(MenuItem). Toolbar view presents us another method to achieve this, toolbar.setNavigationOnClickListener(View.OnClickListener).
To exemplify, I tried to use balysv's MaterialMenuIcon with this method instead of .onOptionsItemSelected(MenuItem) as follows:
private void setupToolbar() {
toolbar = (Toolbar) ((LinearLayout) findViewById(R.id.app_bar)).getChildAt(0);
setSupportActionBar(toolbar);
toolbar.setNavigationOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (drawerLayout.isDrawerVisible(GravityCompat.START)) {
drawerLayout.closeDrawer(GravityCompat.START);
materialMenu.animatePressedState(MaterialMenuDrawable.IconState.BURGER);
} else {
drawerLayout.openDrawer(GravityCompat.START);
materialMenu.animatePressedState(MaterialMenuDrawable.IconState.ARROW);
}
}
});
materialMenu = new MaterialMenuIconToolbar(this, Color.WHITE, MaterialMenuDrawable.Stroke.THIN) {
#Override public int getToolbarViewId() {
return R.id.toolbar;
}
};
drawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
drawerLayout.setDrawerListener(new DrawerLayout.SimpleDrawerListener() {
#Override
public void onDrawerSlide(View drawerView, float slideOffset) {
super.onDrawerSlide(drawerView, slideOffset);
materialMenu.setTransformationOffset(
MaterialMenuDrawable.AnimationState.BURGER_ARROW,
isDrawerOpened ? 2 - slideOffset : slideOffset
);
}
#Override
public void onDrawerOpened(View drawerView) {
super.onDrawerOpened(drawerView);
isDrawerOpened = true;
}
#Override
public void onDrawerClosed(View drawerView) {
super.onDrawerClosed(drawerView);
isDrawerOpened = false;
}
#Override
public void onDrawerStateChanged(int newState) {
super.onDrawerStateChanged(newState);
if (newState == DrawerLayout.STATE_IDLE) {
if (isDrawerOpened) materialMenu.setState(MaterialMenuDrawable.IconState.ARROW);
else materialMenu.setState(MaterialMenuDrawable.IconState.BURGER);
}
}
});
}
I hope it helps.
I am using Xamarin Android, and for AppCompatActivity I also used this method which did not work for me.
SupportActionBar.SetHomeButtonEnabled(true);
but after finding on internet and I found another method, which worked for me, and showed the home navigation button.
SupportActionBar.SetDisplayHomeAsUpEnabled(true);

Categories

Resources