Home button is not clickable - java

Inside my SettingsActivity extends AppCompatActivity I have SettingsFragment extends PreferenceFragment. When I try press home-buttion in toolbar it is not working. Here is my code
toolbar.xml
<?xml version="1.0" encoding="utf-8"?>
<android.support.v7.widget.Toolbar
xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/settingsToolbar"
android:layout_width="match_parent"
android:clickable="true"
android:focusable="true"
android:focusableInTouchMode="true"
android:layout_height="?android:actionBarSize"
android:background="#color/colorPrimary" />
SettingsActivity
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setupToolBar();
getFragmentManager().beginTransaction()
.replace(android.R.id.content, new SettingsFragment())
.commit();
}
private void setupToolBar() {
getLayoutInflater().inflate(R.layout.toolbar, (ViewGroup) findViewById(android.R.id.content));
Toolbar toolbar = (Toolbar) findViewById(R.id.settingsToolbar);
setSupportActionBar(toolbar);
setTitle(getResources().getString(R.string.settings));
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
toolbar.setFocusable(true);
toolbar.setNavigationOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
onBackPressed();
}
});
}
I tried to solve it in such way: remove setNavigationOnClickListener and add this:
#Override
public boolean onOptionsItemSelected(MenuItem menuItem) {
switch (menuItem.getItemId()) {
case android.R.id.home:
onBackPressed();
return true;
}
return (super.onOptionsItemSelected(menuItem));
}
It does not help. How can I fix this?

add this line to config your getSupportActionBar:
getSupportActionBar().setHomeButtonEnabled(true);
use both code in your activity like below:
in your setupToolbar method:
toolbar.setNavigationOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// Log.d("cek", "home selected");
finish();
}
});
and in your onOptionsItemSelected method:
if (item.getItemId() == android.R.id.home) {
finish();
}
return super.onOptionsItemSelected(item);

Related

Why does my BottomNavigationView is not showing up?

I'm trying to add a BottomNavigationView in my project but don't show up when i run the project.
I'd like to put this on several activities, aswell as Toolbar so i created a class that initialize both of them and extends AppCompatActivity so that my activies using the Toolbar or the BottomNavigationView just have to extends this activity and call the method that initialize it (i don't know if this is the right method to use, if no please tell me). So this work with my Toolbar, but my BottomNavigationView isn't showing up.
This is my NavigationActivity i talked about :
public abstract class NavigationActivity extends AppCompatActivity {
private Toolbar mToolbar;
private BottomNavigationView mNavigationView;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
public void initNavigation(int navigationId) {
mNavigationView = (BottomNavigationView) findViewById(navigationId);
mNavigationView.setOnNavigationItemSelectedListener(new BottomNavigationView.OnNavigationItemSelectedListener() {
#Override
public boolean onNavigationItemSelected(#NonNull MenuItem menuItem) {
switch (menuItem.getItemId()) {
case R.id.navigation_entrainements:
startActivity(new Intent(getBaseContext(),MenuEntrainementsActivity.class));
break;
case R.id.navigation_nutrition:
startActivity(new Intent(getBaseContext(),NutritionActivity.class));
break;
case R.id.navigation_statistiques:
startActivity(new Intent(getBaseContext(),StatistiquesActivity.class));
break;
}
return true;
}
});
}
public void initToolbar(int toolbarId) {
mToolbar = (Toolbar) findViewById(toolbarId);
mToolbar.setNavigationIcon(R.drawable.baseline_arrow_back_black_18dp);
setSupportActionBar(mToolbar);
getSupportActionBar().setDisplayShowTitleEnabled(false);
mToolbar.setNavigationOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View view) {
finish();
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.menu,menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.btnHome :
startActivity(new Intent(this,MainActivity.class));
return true;
case R.id.btnProfil :
startActivity(new Intent(this,ProfilActivity.class));
return true;
default :
return super.onOptionsItemSelected(item);
}
}
}
and an exemple of how i'm using it in others activities :
initNavigation(R.id.navigation);
initToolbar(R.id.toolbar);
this is how i implement the BottomNavigationView in my XML files :
<android.support.design.widget.BottomNavigationView
android:id="#+id/navigation"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_marginStart="0dp"
android:layout_marginEnd="0dp"
android:background="?android:attr/windowBackground"
app:menu="#menu/navigation" />
if you need anything else just ask,
thanks for your help :)
(sorry if i made mistakes i'm not great in english)
I Use this from outside of onCreate mothod.
private BottomNavigationView.OnNavigationItemSelectedListener mOnNavigationItemSelectedListener
= new BottomNavigationView.OnNavigationItemSelectedListener() {
#Override
public boolean onNavigationItemSelected(#NonNull MenuItem item) {
Fragment fragment;
switch (item.getItemId()) {
case R.id.btnHome :
startActivity(new Intent(this,MainActivity.class));
return true;
case R.id.btnProfil :
startActivity(new Intent(this,ProfilActivity.class));
return true;
default :
startActivity(new Intent(this,MainActivity.class));
return true;
}
}
};

Menu item click in a navigation drawer intent to activity hosting a fragment

Disclaimer: This is the first app I am building so I am learning the hard way to use fragments first, so my code is all over the place.
I have menu items inside a navigation view that loads fine however the menu item clicks don't work. It doesn't crash it just stares at me. I would like to use an intent to display a fragment and I am lost from changing and trying so many different options.
XML FOR NAV DRAWER & MENU ITEMS:
<android.support.v4.widget.DrawerLayout
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/activity_pageone"
android:background="#drawable/rygg"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:scrollbarThumbVertical="#color/primary_dark_color"
tools:openDrawer="start"
tools:context="com.android.nohiccupsbeta.pageone">
<FrameLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/fragmentContainer"
android:layout_width="match_parent"
android:layout_height="match_parent" >
<android.support.design.widget.NavigationView
android:id="#+id/navigation_header_container"
app:headerLayout="#layout/header"
android:layout_width="wrap_content"
android:layout_height="match_parent"
app:itemIconTint="#color/category_vodka"
app:itemTextColor="#color/primary_dark_color"
app:menu="#menu/drawermenu"
android:layout_gravity="start" >
</android.support.design.widget.NavigationView>
</FrameLayout>
</android.support.v4.widget.DrawerLayout>
JAVA:
public class pageone extends AppCompatActivity implements NavigationView.OnNavigationItemSelectedListener {
DrawerLayout mDrawerLayout;
ActionBarDrawerToggle mToggle;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_pageone);
setupDrawer();
}
#Override
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
mToggle.onConfigurationChanged(newConfig);
}
#Override
public boolean onCreateOptionsMenu(Menu menu){
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.drawermenu, menu);
return true;
}
/**
*
* #param item For the hamburger button
* #return
*/
#Override
public boolean onOptionsItemSelected(MenuItem item) {
if (mToggle.onOptionsItemSelected(item)){
return true;
}
switch (item.getItemId()) {
case R.id.itemWhiskey:
Intent whiskeyIntent = new Intent(pageone.this, whiskeyActivity.class);
startActivity(whiskeyIntent);
return true;
default:
return super.onOptionsItemSelected(item);
}
}
/**
* Make sure the drawer open and closes in sync with UI visual
* #param savedInstanceState
*/
#Override
protected void onPostCreate(Bundle savedInstanceState) {
super.onPostCreate(savedInstanceState);
mToggle.syncState();
}
/**
* Function to make sure all the drawer open & closes properly
*/
public void setupDrawer() {
getSupportActionBar().setHomeButtonEnabled(true);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
mDrawerLayout = (DrawerLayout) findViewById(R.id.activity_pageone);
mToggle = new ActionBarDrawerToggle(this, mDrawerLayout, R.string.drawer_open, R.string.drawer_closed) {
#Override
public void onDrawerClosed(View closeView) {
Toast.makeText(pageone.this, "Happy You Learned", Toast.LENGTH_SHORT).show();
super.onDrawerClosed(closeView);
invalidateOptionsMenu();
}
#Override
public void onDrawerOpened(View openView) {
Toast.makeText(pageone.this, "Effects Of Alcohol", Toast.LENGTH_SHORT).show();
super.onDrawerOpened(openView);
invalidateOptionsMenu();
}
};
mDrawerLayout.addDrawerListener(mToggle);
}
#Override
public boolean onNavigationItemSelected(#NonNull MenuItem item) {
MenuItem itemWhiskey = (MenuItem) findViewById(R.id.itemWhiskey);
itemWhiskey.setOnMenuItemClickListener(new MenuItem.OnMenuItemClickListener() {
#Override
public boolean onMenuItemClick(MenuItem itemWhiskey) {
FragmentManager fm = getSupportFragmentManager();
Fragment effectsFragment = fm.findFragmentById(R.id.frame_container2);
if (effectsFragment == null) {
effectsFragment = new WhiskeyFragment();
fm.beginTransaction().add(R.id.frame_container2, effectsFragment).commit();
getSupportActionBar().setTitle("Whiskey");
itemWhiskey.setChecked(true);
mDrawerLayout.closeDrawers();
}
return true;
}
});
mDrawerLayout.closeDrawer(GravityCompat.START);
return true;
}
}
XML FOR FRAGMENT:
<FrameLayout 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/frame_container2"
tools:context="com.android.nohiccupsbeta.WhiskeyFragment">
<!-- TODO: Update blank fragment layout -->
<TextView
android:id="#+id/frag_whiskey_skin"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginLeft="10dp"
android:layout_marginRight="10dp"
android:layout_marginTop="8dp"
android:textColor="#000000"
android:textSize="16sp" />
<ImageButton
android:id="#+id/expand_collapse"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="end|bottom"
android:background="#android:color/transparent"
android:src="#drawable/ic_expand_more"
android:padding="16dp"/>
</FrameLayout>
JAVA:
public class WhiskeyFragment extends Fragment {
private TextView mWhiskeySkin;
#Override
public void onViewCreated(View view, #Nullable Bundle SavedInstanceState) {
super.onViewCreated(view, SavedInstanceState);
getActivity().setTitle("WHISKEY EFFECTS");
mWhiskeySkin = (TextView) view.findViewById(R.id.frag_whiskey_skin);
mWhiskeySkin.setText(R.string.whiskey_skin);
hasOptionsMenu();
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View v = inflater.inflate(R.layout.fragment_whiskey, container, false);
hasOptionsMenu();
return v;
}
}
XML FOR SECOND ACTIVITY:
<?xml version="1.0" encoding="utf-8"?>
<FrameLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/frame_container"
android:layout_width="match_parent"
android:layout_height="match_parent"/>
JAVA:
public class whiskeyActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_whiskey);
}
public class Whiskeyed {
private String whiskeySkin;
private String whiskeyBrain;
public String getWhiskeySkin(){
return whiskeySkin;
}
public String getWhikeyBrain(){
return whiskeyBrain;
}
public void setWhiskeySkin(String whiskey_skin){
this.whiskeySkin = whiskey_skin;
}
public void setWhiskeyBrain(String whiskeyBrain) {
this.whiskeyBrain = whiskeyBrain;
}
}
}
try to change to content of your onNavigationItemSelected of your pageone.java
from here:
#Override
public boolean onNavigationItemSelected(#NonNull MenuItem item) {
MenuItem itemWhiskey = (MenuItem) findViewById(R.id.itemWhiskey);
itemWhiskey.setOnMenuItemClickListener(new MenuItem.OnMenuItemClickListener() {
#Override
public boolean onMenuItemClick(MenuItem itemWhiskey) {
FragmentManager fm = getSupportFragmentManager();
Fragment effectsFragment = fm.findFragmentById(R.id.frame_container2);
if (effectsFragment == null) {
effectsFragment = new WhiskeyFragment();
fm.beginTransaction().add(R.id.frame_container2, effectsFragment).commit();
getSupportActionBar().setTitle("Whiskey");
itemWhiskey.setChecked(true);
mDrawerLayout.closeDrawers();
}
return true;
}
});
mDrawerLayout.closeDrawer(GravityCompat.START);
return true;
}
to here:
#Override
public boolean onNavigationItemSelected(#NonNull MenuItem item) {
DrawerLayout mDrawerLayout = (DrawerLayout) findViewById(R.id.activity_pageone); // ID of your drawerLayout
int id = item.getItemId();
switch (id) {
case R.id.menu1: // Change this as your menuitem in menu.xml.
// Your fragment code goes here..
FragmentManager fm = getSupportFragmentManager();
Fragment effectsFragment = fm.findFragmentById(R.id.frame_container2);
if (effectsFragment == null) {
effectsFragment = new WhiskeyFragment();
fm.beginTransaction().add(R.id.frame_container2, effectsFragment).commit();
getSupportActionBar().setTitle("Whiskey");
itemWhiskey.setChecked(true);
mDrawerLayout.closeDrawers();
}
break;
case R.id.menu2: // Change this as your menuitem in menu.xml.
// or Your fragment code goes here...
break;
}
mDrawerLayout.closeDrawer(GravityCompat.START, true);
return true;
}

how to get value of switch button from secondActivity?

In my project i have 2 activity , in second activity i have a switch button .
i have 2 problems :
1: I want to get the value of switch button from second activity and pass it to first activity by using shared preferences to show a toast in first activity but i do not get the value of switch button so toast does not work correctly .
2:When i press back or close application , the value of switch button change to default , how can i save the value of switch button ?
This is my first activity :
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
SharedPreferences settings = PreferenceManager.getDefaultSharedPreferences(this);
Boolean isChecked = settings.getBoolean("status" , false);
if (isChecked){
Toast.makeText(this, "Enabled", Toast.LENGTH_SHORT).show();
}else {
Toast.makeText(this, "Disabled", Toast.LENGTH_SHORT).show();
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater menuInflater = getMenuInflater();
menuInflater.inflate(R.menu.menu, menu);
return super.onCreateOptionsMenu(menu);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()){
case R.id.action_setting:
Intent settingIntent = new Intent(getApplicationContext(), Main2Activity.class);
startActivity(settingIntent);
return true;
}
return super.onOptionsItemSelected(item);
}
}
And this is my second activity :
public class Main2Activity extends AppCompatActivity {
Switch aSwitch;
EditText editText;
Button back;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main2);
editText = (EditText) findViewById(R.id.editText);
aSwitch = (Switch) findViewById(R.id.switch1);
back = (Button) findViewById(R.id.btnBack);
back.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent swIntent = new Intent(Main2Activity.this, MainActivity.class);
startActivity(swIntent);
}
});
}
#Override
public void onBackPressed() {
super.onBackPressed();
}
#Override
protected void onSaveInstanceState(Bundle outState) {
outState.putBoolean("MySwitch", true);
super.onSaveInstanceState(outState);
}
public void enable_disable(View view) {
if (aSwitch.isChecked()) {
SharedPreferences.Editor editor = getSharedPreferences("switch", MODE_PRIVATE).edit();
editor.putBoolean("status", true);
editor.commit();
} else {
SharedPreferences.Editor editor = getSharedPreferences("switch", MODE_PRIVATE).edit();
editor.putBoolean("status", false);
editor.commit();
}
}
}
And this is the layout of my second activity :
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:layout_centerInParent="true"
android:gravity="center"
tools:context="a.switchtest.Main2Activity">
<Switch
android:id="#+id/switch1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:onClick="enable_disable"
android:text="Switch" />
<EditText
android:id="#+id/editText"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
<Button
android:id="#+id/btnBack"
android:text="Back"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
Use switch onChangedListener. This will retain your switch state in your Main2Activity
public class Main2Activity extends AppCompatActivity {
Switch aSwitch;
Button back;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main2);
aSwitch = (Switch) findViewById(R.id.switch1);
SharedPreferences sharedPreference = getSharedPreferences("switch", MODE_PRIVATE);
boolean isChecked = sharedPreference.getBoolean("status",false);
Log.d("Shriyansh",isChecked+"");
aSwitch.setChecked(isChecked);
aSwitch.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
// do something, the isChecked will be
// true if the switch is in the On position
SharedPreferences.Editor editor = getSharedPreferences("switch", MODE_PRIVATE).edit();
editor.putBoolean("status", isChecked);
editor.commit();
Log.d("Shriyansh1",isChecked+"");
}
});
back = (Button) findViewById(R.id.btnBack);
back.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent swIntent = new Intent(Main2Activity.this, MainActivity.class);
startActivity(swIntent);
}
});
}
Now to show toast in your first activity you can use this preference in onResume() method of your MainActivity
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
#Override
protected void onResume() {
super.onResume();
SharedPreferences sharedPreference = getSharedPreferences("switch", MODE_PRIVATE);
boolean isChecked = sharedPreference.getBoolean("status",false);
if (isChecked){
Toast.makeText(this, "Enabled", Toast.LENGTH_SHORT).show();
}else {
Toast.makeText(this, "Disabled", Toast.LENGTH_SHORT).show();
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater menuInflater = getMenuInflater();
menuInflater.inflate(R.menu.menu, menu);
return super.onCreateOptionsMenu(menu);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()){
case R.id.action_setting:
Intent settingIntent = new Intent(getApplicationContext(),
Main2Activity.class);
startActivity(settingIntent);
return true;
}
return super.onOptionsItemSelected(item);
}
}
Layout of your Main2Activity remove enable_disable method for switch
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:layout_centerInParent="true"
android:gravity="center"
tools:context="a.switchtest.Main2Activity">
<Switch
android:id="#+id/switch1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Switch" />
<EditText
android:id="#+id/editText"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
<Button
android:id="#+id/btnBack"
android:text="Back"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
in you MainActivity you need to replace
PreferenceManager.getDefaultSharedPreferences(this);
with
SharedPreferences sharedPreference = getSharedPreferences("switch", MODE_PRIVATE);
also remove this from your Main2Activity
#Override
protected void onSaveInstanceState(Bundle outState) {
outState.putBoolean("MySwitch", true);
super.onSaveInstanceState(outState);
}
SharedPreferences are just key value xml files stored on the device. The problem you are having is that you are using two different SharedPreferences which is why the value is not showing up.
In your SecondActivity where you use the line:
getSharedPreferences("switch", MODE_PRIVATE).edit();
You are creating a SharedPreferences file called switch.xml and storing the value of your switch in it. However in your MainActivity when you call:
PreferenceManager.getDefaultSharedPreferences(this);
This fetches the 'default file' which is a different xml file and as such the value is not there. You need to be consistent with which SharedPreferences file you are accessing between the two Activities. In this case I'd recommend just using the default file and changing your SecondActivity to be:
SharedPreferences.Editor editor = PreferenceManager
.getDefaultSharedPreferences(this)
.edit();
editor.putBoolean("status", true);
editor.commit();
Now the value will be saved in the default file which is the same one which your reading in the MainActivity

Toolbar isn't following into next activity

I'm working on an app and I would like to have a toolbar going into each and every activity. I set up the toolbar into the primary activity, but when I click the item in the toolbar that sends me to the next activity, the toolbar isn't shown. I have included the toolbar in both .xml files. When I run the second activity by itself, the toolbar is shown. Any help please?
HomeActivty Java:
private Toolbar toolbar;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_home);
toolbar = (Toolbar) findViewById(R.id.tToolbar);
setSupportActionBar(toolbar);
}
#Override
public boolean onCreateOptionsMenu(Menu menu)
{
MenuInflater menuInflater = getMenuInflater();
menuInflater.inflate(R.menu.menu_home,menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item)
{
int res_id = item.getItemId();
if(res_id == R.id.action_profile)
{
Intent profileActivity = new Intent(HomeActivity.this,
ProfileActivity.class);
startActivity(profileActivity);
finish();
overridePendingTransition(R.anim.push_left_in,
R.anim.push_left_out);
}
else if(res_id == R.id.action_home)
{
}
else if(res_id == R.id.action_msg)
{
Intent cnectActivity = new Intent(HomeActivity.this,
ConnectionsActivity.class);
startActivity(cnectActivity);
finish();
overridePendingTransition(R.anim.push_left_in,
R.anim.push_left_out);
}
return true;
}
}
ProfileActivity java:
private Toolbar toolbar;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_profile);
toolbar = (Toolbar) findViewById(R.id.tToolbar);
setSupportActionBar(toolbar);
}
#Override
public boolean onCreateOptionsMenu(Menu menu)
{
MenuInflater menuInflater = getMenuInflater();
menuInflater.inflate(R.menu.menu_home,menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item)
{
int res_id = item.getItemId();
if(res_id == R.id.action_profile)
{
}
else if(res_id == R.id.action_home)
{
Intent profileActivity = new Intent(ProfileActivity.this,
HomeActivity.class);
startActivity(profileActivity);
finish();
overridePendingTransition(R.anim.push_left_in,
R.anim.push_left_out);
}
else if(res_id == R.id.action_msg)
{
Intent cnectActivity = new Intent(ProfileActivity.this,
ConnectionsActivity.class);
startActivity(cnectActivity);
finish();
overridePendingTransition(R.anim.push_left_in,
R.anim.push_left_out);
}
return true;
}
}
toolbar xml:
<android.support.v7.widget.Toolbar
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:background="#color/colorPrimary"
app:theme="#style/AppThemePenis"
android:elevation="4dp"
>
<Button
android:layout_width="match_parent"
android:layout_height="match_parent"
android:text="P"/>
</android.support.v7.widget.Toolbar>
I'm using Android Studio.

Set Toolbar Home Navigation Button to Follow backstack, Android

I have set up a toolbar and added a home navigation button as follows;
Toolbar toolbar;
toolbar = (Toolbar) findViewById(R.id.toolbar_home);
//Setup toolbar
toolbar.setTitle("Home");
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
toolbar.setTitleTextColor(getResources().getColor(R.color.icons,null));
}else{
toolbar.setTitleTextColor(getResources().getColor(R.color.icons));
}
setSupportActionBar(toolbar);
if (getSupportActionBar() != null) {
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setDisplayShowHomeEnabled(true);
} else {
Log.w("Home", "toolbar null");
}
toolbar.setNavigationOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//Navigate backwards as android back button
}
});
I want when i press the toolbar backbutton, it navigates backwards following the backstack as the the android backbutton.enter image description here
add this method in activity:
#Override
public boolean onOptionsItemSelected(MenuItem item)
{
if(item.getItemId() == android.R.id.home){
onBackPressed();
return true;
}
return super.onOptionsItemSelected(item);
}
I am following this from long time and not found any issue yet .
HomeFragment : First fragment which getting loaded first time
getFragmentManager().addOnBackStackChangedListener(new FragmentManager.OnBackStackChangedListener() {
#Override
public void onBackStackChanged() {
HomeFragment currentHomeFragment = null;
currentHomeFragment = (HomeFragment) getFragmentManager().findFragmentByTag("HOME_FRAGMENT");
if (currentHomeFragment != null && currentHomeFragment.isVisible()) {
getSupportActionBar().setDisplayHomeAsUpEnabled(false);
toggle.syncState();
toolbar.setNavigationOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
drawer.openDrawer(GravityCompat.START);
}
});
} else {
if (getFragmentManager().getBackStackEntryCount() > 1) {
getSupportActionBar().setDisplayHomeAsUpEnabled(true); // show back button
toolbar.setNavigationOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
getFragmentManager().popBackStackImmediate();
}
});
} else {
getSupportActionBar().setDisplayHomeAsUpEnabled(false);
toggle.syncState();
toolbar.setNavigationOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
drawer.openDrawer(GravityCompat.START);
}
});
}
}
}
});
If you are using android.support.v7.widget.Toolbar add this code to your AppCompatActivity:
#Override
public boolean onSupportNavigateUp() {
onBackPressed();
return true;
}
in your onClick write onBackPressed(); or in manifest
<activity android:name=".XYZActivity"
android:parentActivityName=".MainActivity" />
Setup toolbar in MainActivity onCreate() method.
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar_home);
toolbar.setTitle("Activity Name");
setSupportActionBar(toolbar);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setDisplayShowHomeEnabled(true);
Setup back navigation by implementing below method in MainActivity Level.
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home:
onBackPressed();
return true;
default:
return super.onOptionsItemSelected(item);
}
}
Works well..
#Rajesh

Categories

Resources