Toolbar isn't following into next activity - java

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.

Related

How to add navigation drawer toggle to a toolbar

I have done everything, I can see the navigation drawer but my app is crashing. Can anyone explain whats the problem in the below code. Now whenever I try to open ForumActivty it is crashing.
public class ForumActivity extends AppCompatActivity implements AdvancedWebView.Listener{
public AdvancedWebView webView;
private ProgressBar mPbar = null;
private static final String url = "https://discuss.flarum.org/";
String webURL, webTitle ;
private DrawerLayout mDrawerLayout;
private Fragment fragment;
private FragmentManager fragmentManager;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
((CustomApplication)getApplication()).checkUserLogin();
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
setContentView(R.layout.activity_forum);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
drawer.setDrawerListener(toggle);
toggle.syncState();
Bundle bundle = getIntent().getExtras();
if(bundle != null){
fragment = new ProfileFragment();
}else{
fragment = new TopicFragment();
}
fragmentManager = getSupportFragmentManager();
FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
fragmentTransaction.replace(R.id.fragment_content, fragment).commit();
NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
navigationView.setNavigationItemSelectedListener(new NavigationView.OnNavigationItemSelectedListener() {
#Override
public boolean onNavigationItemSelected(#NonNull MenuItem item) {
int id = item.getItemId();
if (id == R.id.nav_topic) {
fragment = new TopicFragment();
}
else if(id == R.id.nav_profile){
fragment = new ProfileFragment();
}
else if(id == R.id.nav_scores){
fragment = new ScoreFragment();
}
else if(id == R.id.nav_share){
fragment = new ScoreFragment();
}
else if(id == R.id.nav_contact){
startActivity(new Intent(ForumActivity.this, ContactActivity.class));
}
else if(id == R.id.nav_settings){
fragment = new SettingsFragment();
}
else if(id == R.id.nav_logout){
((CustomApplication)getApplication()).getShared().setUserData("");
Intent logoutIntent = new Intent(ForumActivity.this, LoginActivity.class);
logoutIntent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK | Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(logoutIntent);
finish();
}
FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
ft.replace(R.id.fragment_content, fragment).commit();
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
drawer.closeDrawer(GravityCompat.START);
return true;
}
});
mPbar = (ProgressBar) findViewById(R.id.loader);
webView = (AdvancedWebView) findViewById(R.id.newWeb);
webView.loadUrl(url);
webView.setListener(this, this);
WebSettings webSettings = webView.getSettings();
webSettings.setJavaScriptEnabled(true);
webSettings.setAppCacheEnabled(true);
webSettings.setDomStorageEnabled(true);
webSettings.setCacheMode(WebSettings.LOAD_DEFAULT);
webSettings.setAllowFileAccess(true);
CookieManager cookieManager = CookieManager.getInstance();
cookieManager.setAcceptCookie(true);
webView.setWebChromeClient(new WebChromeClient() {
#Override
public boolean onCreateWindow(WebView view, boolean isDialog, boolean isUserGesture, Message resultMsg) {
AdvancedWebView newWebView = new AdvancedWebView(ForumActivity.this);
WebView.WebViewTransport transport = (WebView.WebViewTransport) resultMsg.obj;
transport.setWebView(newWebView);
resultMsg.sendToTarget();
return true;
}
});
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
webView.setLayerType(View.LAYER_TYPE_HARDWARE, null);
webSettings.setAllowUniversalAccessFromFileURLs(true);
} else {
webView.setLayerType(View.LAYER_TYPE_SOFTWARE, null);
}
webView.setWebViewClient(new WebViewClient(){
#Override
public void onPageStarted(WebView view, String url, Bitmap favicon) {
mPbar.setVisibility(View.VISIBLE);
}
public void onPageFinished(WebView view, String url) {
mPbar.setVisibility(View.GONE);
}
});
webView.setOnKeyListener( new View.OnKeyListener() {
#Override
public boolean onKey( View v, int keyCode, KeyEvent event ) {
if ((keyCode == KeyEvent.KEYCODE_BACK) && webView.canGoBack()) {
webView.goBack();
return true;
}
return false;
}
});
webView.setThirdPartyCookiesEnabled(true);
webView.setCookiesEnabled(true);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home:
mDrawerLayout.openDrawer(GravityCompat.START);
return true;
}
return super.onOptionsItemSelected(item);
}
#Override
protected void onResume() {
super.onResume();
webView.onResume();
}
#Override
protected void onPause() {
webView.onPause();
super.onPause();
}
#Override
protected void onDestroy() {
webView.onDestroy();
super.onDestroy();
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent intent) {
super.onActivityResult(requestCode, resultCode, intent);
webView.onActivityResult(requestCode, resultCode, intent);
}
#Override
public void onBackPressed() {
if (!webView.onBackPressed()) { return; }
super.onBackPressed();
}
#Override
public void onPageStarted(String url, Bitmap favicon) {
}
#Override
public void onPageFinished(String url) {
webURL = webView.getUrl();
webTitle = webView.getTitle();
}
#Override
public void onPageError(int errorCode, String description, String failingUrl) {
}
#Override
public void onDownloadRequested(String url, String suggestedFilename, String mimeType, long contentLength, String contentDisposition, String userAgent) {
}
#Override
public void onExternalPageRequest(String url) {
}
}
I know I am doing something wrong above but I have included everything in layout. It would be really nice if someone can help
You should have also shared the code of layout&activity which already has a Navigation Drawer. Anyway, you can follow this guide.
For you layout file, you will need to put your CoordinatorLayout inside DrawerLayout like this and add a NavigationView (check the xml layout of other Activity which already has a navigation drawer and copy <android.support.design.widget.NavigationView> and replace with the one in below example):
<android.support.v4.widget.DrawerLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:id="#+id/drawer_layout"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:fitsSystemWindows="true">
<android.support.design.widget.CoordinatorLayout
xmlns:app="http://schemas.android.com/apk/res-auto"
android:id="#+id/coordinator_layout"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:fitsSystemWindows="true">
<android.support.design.widget.AppBarLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:theme="#style/AppTheme.AppBarOverlay">
<android.support.v7.widget.Toolbar
android:id="#+id/toolbar"
android:layout_width="match_parent"
android:layout_height="?attr/actionBarSize"
android:background="?attr/colorPrimary"
app:popupTheme="#style/AppTheme.PopupOverlay" />
</android.support.design.widget.AppBarLayout>
<im.delight.android.webview.AdvancedWebView
android:id="#+id/newWeb"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
app:layout_behavior="#string/appbar_scrolling_view_behavior"
></im.delight.android.webview.AdvancedWebView>
<ProgressBar
style="?android:attr/progressBarStyleLarge"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/loader"
android:layout_weight="1"
android:layout_gravity="center_vertical|center_horizontal|center"/>
</android.support.design.widget.CoordinatorLayout>
<!-- Replace this with the one in other activity layout -->
<android.support.design.widget.NavigationView
android:id="#+id/nav_view"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:layout_gravity="start"
android:fitsSystemWindows="true"
app:menu="#menu/drawer_view"/>
</android.support.v4.widget.DrawerLayout>
After that there will be some code that you will need to add in your Activity class. You can check the link I put above and after reading it you can understand which code you need to copy from other Activity which already has a navigation drawer.

onOptionsItemSelected not working

I'm making a navigation drawer that slides into the screen. I did this with this code
<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android">
<item android:id="#+id/home" android:title="Home"></item>
<item android:id="#+id/change_event" android:title="Change Event"></item>
<item android:id="#+id/FAQ" android:title="FAQ"></item>
<item android:id="#+id/map" android:title="Map"></item>
<item android:id="#+id/Schedule" android:title="Schedule"></item>
</menu>
Now in the MainActivity.Java, I'm trying to switch between activities with the OnOptionsItemSelected method. I'm trying this with this code.
#Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
if (id == R.id.home){
Intent intent = new Intent(MainActivity.this, Home.class);
startActivity(intent);
}
return true;
}
What I want this code to do is when if you open the slide menu and click on the home item, the activity home has to start. This is not working, and I have no idea what I am doing wrong.
You have to add onCreateOptionsMenu
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.your_menu_file_name, menu);
return true;
}
Updated:
NavigationDrawer class
public class MainActivityNew extends AppCompatActivity
implements NavigationView.OnNavigationItemSelectedListener {
#BindView(R.id.toolbar)
Toolbar toolbar;
#BindView(R.id.nav_view)
NavigationView navView;
#BindView(R.id.drawer_layout)
DrawerLayout drawerLayout;
public static final String TAG_HOME = "Dashboard";
public static final String TAG_TEMP = "Temperature";
public static String CURRENT_TAG = TAG_HOME;
public static int navItemIndex = 0;
public Fragment fragment;
private Fragment sendFragment;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main_new);
ButterKnife.bind(this);
setSupportActionBar(toolbar);
if (savedInstanceState != null) {
fragment = getSupportFragmentManager().getFragment(savedInstanceState, "myFragmentName");
FragmentTransaction fragmentTransaction = getSupportFragmentManager().beginTransaction();
fragmentTransaction.setCustomAnimations(android.R.anim.fade_in,
android.R.anim.fade_out);
fragmentTransaction.replace(R.id.frame, fragment, CURRENT_TAG);
fragmentTransaction.commit();
} else {
navItemIndex = 0;
CURRENT_TAG = TAG_HOME;
loadHomeFragment();
}
ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(this, drawerLayout, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
drawerLayout.setDrawerListener(toggle);
toggle.syncState();
navView.setNavigationItemSelectedListener(this);
}
private void loadHomeFragment() {
selectNavMenu();
if (getSupportFragmentManager().findFragmentByTag(CURRENT_TAG) != null) {
drawerLayout.closeDrawers();
return;
} else {
fragment = getHomeFragment();
FragmentTransaction fragmentTransaction = getSupportFragmentManager().beginTransaction();
fragmentTransaction.setCustomAnimations(android.R.anim.fade_in,
android.R.anim.fade_out);
fragmentTransaction.replace(R.id.frame, fragment, CURRENT_TAG);
fragmentTransaction.commit();
drawerLayout.closeDrawers();
}
}
private Fragment getHomeFragment() {
switch (navItemIndex) {
case 0:
sendFragment = new HomeFragment();
break;
case 1:
sendFragment = new TemperatureFragment();
break;
default:
sendFragment = new TemperatureFragment();
}
return sendFragment;
}
private void selectNavMenu() {
navView.getMenu().getItem(navItemIndex).setChecked(true);
}
#Override
public void onBackPressed() {
if (drawerLayout.isDrawerOpen(GravityCompat.START)) {
drawerLayout.closeDrawer(GravityCompat.START);
return;
}
super.onBackPressed();
}
#SuppressWarnings("StatementWithEmptyBody")
#Override
public boolean onNavigationItemSelected(MenuItem menuItem) {
switch (menuItem.getItemId()) {
case R.id.home:
navItemIndex = 0;
CURRENT_TAG = TAG_HOME;
break;
case R.id.temperrature_sensor:
navItemIndex = 1;
CURRENT_TAG = TAG_TEMP;
break;
default:
navItemIndex = 0;
}
if (menuItem.isChecked()) {
menuItem.setChecked(false);
} else {
menuItem.setChecked(true);
}
menuItem.setChecked(true);
loadHomeFragment();
return true;
}
#Override
protected void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
getSupportFragmentManager().putFragment(outState, "myFragmentName", fragment);
}
#Override
public void onRestoreInstanceState(Bundle savedInstanceState, PersistableBundle persistentState) {
super.onRestoreInstanceState(savedInstanceState, persistentState);
}
}

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;
}

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

Home button is not clickable

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);

Categories

Resources