Android Toolbar back button not being recognised - java

I am working on an the settings screens for an android appliation.
The settings screen contains 2 'sub screens' both have a toolbar and a have a back button.
The back button on screen 1 does nothing
The back button on screen 1 works perfectly and returns me to the main settings screen (the 'hard' back button works for both screens)
Screen 1 (Preferences Screen):
Screen 1 xml:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/activity_preferences"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.clear.pocketcross.Preferences">
<Toolbar xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/toolbar"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="?android:attr/colorPrimary"
android:popupTheme="#android:style/ThemeOverlay.Material.Light"
android:theme="#android:style/ThemeOverlay.Material.Dark.ActionBar" />
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="#+id/toolbar"
android:orientation="vertical"
android:paddingBottom="#dimen/activity_vertical_margin"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin">
<Switch
android:id="#+id/counterscroll"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:defaultValue="true"
android:key="counter_scroll"
android:shadowColor="#color/gradient_mid"
android:shadowDx="5"
android:shadowDy="5"
android:text="#string/scrollCounters"
android:thumb="#drawable/pocketcross_btn_radio_on_holo_light" />
<Switch
android:id="#+id/navswipe"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:defaultValue="true"
android:key="nav_swipe"
android:shadowColor="#color/gradient_mid"
android:shadowDx="5"
android:shadowDy="5"
android:text="#string/swipeTitle"
android:thumb="#drawable/pocketcross_btn_radio_on_holo_light" />
</LinearLayout>
</RelativeLayout>
Java for Screen 1:
Switch nav;
Switch scroll;
SharedPreferences shared;
public static final String MyPREFERENCES = "PocketCross";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_preferences);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
//Toolbar will now take on default Action Bar characteristics
setActionBar(toolbar);
getActionBar().setDisplayHomeAsUpEnabled(true);
this.setTitle("Preferences");
nav = (Switch) findViewById(R.id.navswipe);
scroll = (Switch) findViewById(R.id.counterscroll);
if (shared == null) {
shared = this.getSharedPreferences(MyPREFERENCES, Context.MODE_PRIVATE);
}
nav.setChecked(shared.getBoolean("nav_swipe", true));
scroll.setChecked(shared.getBoolean("counter_scroll", true));
nav.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
SharedPreferences.Editor spEdit = shared.edit();
spEdit.putBoolean("nav_swipe", isChecked);
spEdit.apply();
}
});
scroll.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
SharedPreferences.Editor spEdit = shared.edit();
spEdit.putBoolean("counter_scroll", isChecked);
spEdit.apply();
}
});
}
Screen 2 (Pocket Cross Parameters Screen):
XML for Screen 2:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/parametersTable"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:shrinkColumns="*"
android:stretchColumns="*"
android:background="#color/background"
android:clickable="false">
<Toolbar xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/toolbar"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="?android:attr/colorPrimary"
android:theme="#android:style/ThemeOverlay.Material.Dark.ActionBar"
android:popupTheme="#android:style/ThemeOverlay.Material.Light" />
<ListView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/parametersList"
android:layout_centerVertical="true"
android:layout_centerHorizontal="true"
android:layout_marginTop="#dimen/activity_vertical_margin"
android:layout_marginBottom="#dimen/activity_vertical_margin"
android:layout_marginLeft="#dimen/activity_horizontal_margin"
android:layout_marginRight="#dimen/activity_horizontal_margin"
android:layout_below="#+id/toolbar" />
</RelativeLayout>
Java for Screen 2: -
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_paramaters);
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
getWindow().addFlags(WindowManager.LayoutParams.FLAG_FORCE_NOT_FULLSCREEN);
getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_HIDDEN);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
//Toolbar will now take on default Action Bar characteristics
setActionBar(toolbar);
getActionBar().setDisplayHomeAsUpEnabled(true);
this.setTitle(R.string.parametersTitle);
mntFile = MainMenu.mntFile;
fileData = xmlTools.getXmlFile(mntFile);
tags = fileData.xmlTags;
for (int i = 0; i < tags.size(); i++) {
tag = tags.get(i);
if (tag.nodeTag.equalsIgnoreCase("PocketCrossSysParam")) {
nodes = tag.nodeData;
paramSetting = xmlTools.getNodeFromList(nodes, "ParamName");
paramValue = xmlTools.getNodeFromList(nodes, "ParamValue");
parameter = new PocketCrossParameter(paramSetting,paramValue);
parameters.add(parameter);
}
}
loadParams();
}
(loadParams is a function to get the various parameters from an xml file)
I have tried adding the following to my code but still the back button does nothing: -
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home:
onBackPressed();
return true;
}
return super.onOptionsItemSelected(item);
}
What I am struggling to understand is why the back button on every single screen in my app works perfectly except this one.
I'm guessing it will be something obvious but I have no idea what.

In your manifest.xml add this line, android:parentActivityName=".(Name of the activity you want to return)"
Just like this
<activity
android:name=".(CurrentActivity)"
android:parentActivityName=".(Activity to be returned)"/>

You can check the following
1) Your activity extend AppCompatActivity
2)
Toolbar mToolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(mToolbar);
getSupportActionBar().setTitle("Title");
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
3) override the following method
#Override
public boolean onOptionsItemSelected(MenuItem item) {
if (item.getItemId()== android.R.id.home) {
finish();
return true;
}
return super.onOptionsItemSelected(item);
}

The issue seems to be with your xml file. You have specified your parent layout as clickable false and hence not getting your click calls. Try removing it.

Related

How to set menu to an AppBarLayout

I'm new to programming, and I want to add a settings menu button.
Like on the picture, my app doesn't show the three dots button.
MainActivity.java :
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
SectionsPagerAdapter sectionsPagerAdapter = new SectionsPagerAdapter(this, getSupportFragmentManager());
ViewPager viewPager = findViewById(R.id.view_pager);
viewPager.setAdapter(sectionsPagerAdapter);
TabLayout tabs = findViewById(R.id.tabs);
tabs.setupWithViewPager(viewPager);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.settings, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(#NonNull MenuItem item) {
switch (item.getItemId()) {
case R.id.vueSatellite:
Toast.makeText(this, "Hi", Toast.LENGTH_SHORT).show();
return true;
default:
return super.onOptionsItemSelected(item);
}
}
}
activity_main.xml :
<?xml version="1.0" encoding="utf-8"?>
<androidx.coordinatorlayout.widget.CoordinatorLayout
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"
tools:context=".MainActivity">
<androidx.viewpager.widget.ViewPager
android:id="#+id/view_pager"
android:layout_width="match_parent"
android:layout_height="match_parent"
app:layout_behavior="#string/appbar_scrolling_view_behavior" />
<com.google.android.material.appbar.AppBarLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:theme="#style/AppTheme">
<TextView
android:id="#+id/title"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:gravity="center"
android:minHeight="?actionBarSize"
android:padding="#dimen/appbar_padding"
android:text="#string/app_name"
android:textColor="#color/colorAccent"
android:textAppearance="#style/TextAppearance.Widget.AppCompat.Toolbar.Title" />
<com.google.android.material.tabs.TabLayout
android:id="#+id/tabs"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#color/White"
app:tabTextColor="#color/colorAccent"/>
</com.google.android.material.appbar.AppBarLayout>
</androidx.coordinatorlayout.widget.CoordinatorLayout>
settings.xml :
<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto">
<item android:id="#+id/vueSatellite"
android:title="#string/item_vue_satellite"
app:showAsAction="never"/>
</menu>
What is my mistake ?
Or what do I have to add?
Tell me if there is missing information like the file AndroidManifest.xml for example.
Thanks
In your Activity just add
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
Hope it works.

the back button and the title is not shown when setup toolbar in android

I'm tying to setup the toolbar in the activity, but the when i set a title and the default back button. it doesn't show anything
public class LaptopDetail extends AppCompatActivity {
Toolbar toolbar;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_laptop_detail);
setupToolbar();
}
void setupToolbar() {
toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
Intent data = getIntent();
getSupportActionBar().setTitle(data.getStringExtra("laptop_name"));
getSupportActionBar().setDisplayShowHomeEnabled(true);
}
public boolean onOptionsItemSelected(MenuItem item){
Intent myIntent = new Intent(getApplicationContext(), BrandOffers.class);
startActivityForResult(myIntent, 0);
return true;
}
}
and here is my xml
<RelativeLayout 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"
tools:context="com.example.ahmed.myapplication3.LaptopDetail">
<RelativeLayout
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="?attr/actionBarSize"
android:background="#273243"
app:layout_scrollFlags="scroll|enterAlways"
app:popupTheme="#style/ThemeOverlay.AppCompat.Light" >
</android.support.v7.widget.Toolbar>
</RelativeLayout>
</RelativeLayout>
is there anything missing in my code, by the way, I'm using the same code in different activity and it is working
thanks in advance
You haven't included the content of your theme style, but I think that's where the problem might be. Check out this answer, I hope it helps.

CollapsingToolbarLayout and toolbar action buttons

I would appreciate if someone could give me some pointers to solve my latest issue.
I have an activity with a CollapsingToolbarLayout. In an un-collapsed state Im unable to get the buttons to work. I do not know how to fix this issue. I have searched on stackoverflow before posting this, but I did not find any helpful tips.
Im posting here hoping for an answer
Thanks
This is my code!
<?xml version="1.0" encoding="utf-8"?>
<android.support.design.widget.CoordinatorLayout 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:background="?attr/app_background"
android:fitsSystemWindows="true"
tools:context="com.company.walt.activities.photos.PhotosAAAActivity">
<android.support.design.widget.AppBarLayout
android:id="#+id/appbar"
android:layout_width="match_parent"
android:layout_height="wrap_content">
<android.support.design.widget.CollapsingToolbarLayout
android:id="#+id/collapsing_toolbar"
android:layout_width="match_parent"
android:layout_height="match_parent"
app:contentScrim="?attr/colorPrimary"
app:layout_scrollFlags="scroll|exitUntilCollapsed">
<RelativeLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content">
<ImageView
android:id="#+id/backdrop"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:adjustViewBounds="true"
android:scaleType="centerCrop"
android:src="#drawable/ip_photo_header"
app:layout_collapseMode="parallax"
app:layout_collapseParallaxMultiplier="0.7" />
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerInParent="true"
android:gravity="center_horizontal"
android:orientation="vertical">
<TextView
android:id="#+id/love_music"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="AAAAAA"
android:textColor="#android:color/white"
android:textSize="#dimen/ssi_txt_40sp" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="BBBBBBBB"
android:textColor="#android:color/white"
android:textSize="#dimen/ssi_txt_20sp" />
</LinearLayout>
</RelativeLayout>
<android.support.v7.widget.Toolbar
android:id="#+id/main_toolbar"
android:layout_width="match_parent"
android:layout_height="?attr/actionBarSize"
android:layout_marginTop="#dimen/ssi_24dp"
app:layout_collapseMode="pin"
app:popupTheme="#style/ThemeOverlay.AppCompat.Light"
app:theme="#style/ThemeOverlay.AppCompat.Dark.ActionBar" />
</android.support.design.widget.CollapsingToolbarLayout>
<android.support.design.widget.TabLayout
android:id="#+id/tab"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="?attr/colorPrimary"
app:tabIndicatorColor="#color/white"
app:tabSelectedTextColor="#color/white"
app:tabTextColor="#color/white" />
</android.support.design.widget.AppBarLayout>
<android.support.v4.view.ViewPager xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/pager"
android:layout_width="match_parent"
android:layout_height="match_parent" />
</android.support.design.widget.CoordinatorLayout>
PhotosAAAActivity.java
public class PhotosAAAActivity extends AppCompatActivity {
//region WIDGETS
private AppBarLayout bAppBarLayout;
private CollapsingToolbarLayout bCollapsingToolbar;
private Toolbar bToolbar;
private TabLayout mTabLayout;
//endregion
//region VARS
private ViewPager mViewPager;
private PhotosPagerAdapter mPhotosPagerAdapter;
SharedPreferencesManager mSharedPreferences;
//endregion
/* ******************************************************************************************* */
//region THE ONCREATE
#Override
protected void onCreate(Bundle savedInstanceState)
{
//region Load Preferences
mSharedPreferences = new SharedPreferencesManager(this);
//endregion
//region Switching theme style
if (mSharedPreferences.getNightModeState() == true) {
setTheme(R.style.NightTheme);
} else {
setTheme(R.style.LightTheme);
}
//endregion
//region Super onCreate
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_photos);
//endregion
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
Window w = getWindow(); // in Activity's onCreate() for instance
w.setFlags(WindowManager.LayoutParams.FLAG_LAYOUT_NO_LIMITS, WindowManager.LayoutParams.FLAG_LAYOUT_NO_LIMITS);
}
//region Calling Methods
setUpCollapsingToolbar();
setUpToolbar();
setViewPager();
//endregion
}
//endregion
private void setUpCollapsingToolbar() {
bCollapsingToolbar = (CollapsingToolbarLayout) findViewById(R.id.collapsing_toolbar);
bCollapsingToolbar.setCollapsedTitleTextColor(getResources().getColor(R.color.white));
bAppBarLayout = (AppBarLayout) findViewById(R.id.appbar);
bAppBarLayout.addOnOffsetChangedListener(new AppBarLayout.OnOffsetChangedListener() {
boolean isShow = false;
int scrollRange = -1;
#Override
public void onOffsetChanged(AppBarLayout appBarLayout, int verticalOffset) {
if (scrollRange == -1) {
scrollRange = appBarLayout.getTotalScrollRange();
}
if (scrollRange + verticalOffset == 0) {
bCollapsingToolbar.setTitle("Post photos");
isShow = true;
} else if (isShow) {
bCollapsingToolbar.setTitle("");
isShow = false;
}
}
});
}
/* ******************************************************************************************* */
//region Used to create the toolbar on top
private void setUpToolbar() {
bToolbar = (Toolbar) findViewById(R.id.main_toolbar);
setSupportActionBar(bToolbar);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setTitle("");
}
//endregion
/* ******************************************************************************************* */
//region Used to create the tab layout
private void setViewPager() {
mViewPager = (ViewPager) findViewById(R.id.pager);
mPhotosPagerAdapter = new PhotosPagerAdapter(getSupportFragmentManager());
mViewPager.setAdapter(mPhotosPagerAdapter);
mTabLayout = (TabLayout) findViewById(R.id.tab);
mTabLayout.setupWithViewPager(mViewPager);
}
//endregion
/* ******************************************************************************************* */
//region MATERIAL DRAWER
#Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.photo_category, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId())
{
case android.R.id.home:
finish();
//Toast.makeText(PhotosAAAActivity.this, "GO BACK", Toast.LENGTH_SHORT).show();
return true;
default:
return super.onOptionsItemSelected(item);
}
}
//endregion
}
UPDATE! - 2018-01-13
I figured out what is cousing the the issue but I still dont know fix this
The problem is that if I remove this code then the tabs won't show up, so it feels as if this ***** with me
The issue
//region Used to create the tab layout
private void setViewPager() {
ViewPager mViewPager = (ViewPager) findViewById(R.id.pager);
mPhotosPagerAdapter = new PhotosPagerAdapter(getSupportFragmentManager());
mViewPager.setAdapter(mPhotosPagerAdapter);
mTabLayout = (TabLayout) findViewById(R.id.tab);
mTabLayout.setupWithViewPager(mViewPager);
}
//endregion
There are two issues with your code, both related to the buttons you're trying to get to work.
First, with the home button (or the up button you need to activate it with actionBar before handling events with it. Add the following:
getSupportActionBar().setHomeButtonEnabled(true);
inside your setupToolbar method. You can now access the button using the code you've written under the case android.R.id.home:.
The second button has the same issue. You haven't added any logic to handle the button click. Let's say your button on the right has id="#+id/more". Now to define an action for it, you need to put a case with its id inside switch like,
case R.id.more:
//The action needed for the button
break;
try this.
in your activity
ActionBar actionBar = getSupportActionBar();
if (actionBar != null) {
actionBar.setHomeButtonEnabled(true);
actionBar.setDisplayHomeAsUpEnabled(true);
}
in your xml
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home:
finish();
break;
//for menu you should give ids to that menu items in your menu file
//R.menu.photo_category and after that if you have 2 menu items
// you have to write listener for every single items for onClick like.
case R.id.item1:
finish();
break;
case R.id.item2:
finish();
break;
}
return 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();
if (id == android.R.id.home) {
finish();
}
//noinspection SimplifiableIfStatement
return super.onOptionsItemSelected(item);
}
Back Button on click listener.

Android Navigation Menu on item selected listener not firing

I have a navigation menu set up but whenever I select an item from it the onNavigationItemSelected does not get called.
MapsActivity.java
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_maps);
initializeMap();
googleApiClient = new GoogleApiClient.Builder(this)
.enableAutoManage(this, this)
.addConnectionCallbacks(this)
.addApi(LocationServices.API)
.build();
navigationMenu = (NavigationView) findViewById(R.id.navigation_menu);
mDrawerLayout = (DrawerLayout)findViewById(R.id.drawer_layout);
mToggle = new ActionBarDrawerToggle(this, mDrawerLayout, R.string.open, R.string.close);
mDrawerLayout.addDrawerListener(mToggle);
mToggle.syncState();
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
toast = Toast.makeText(this, "test", Toast.LENGTH_LONG);
navigationMenu.setNavigationItemSelectedListener(this);
}
#Override
public boolean onNavigationItemSelected(#NonNull MenuItem item) {
toast.show();
Log.v("NAV", "Navigation item selected");
Log.v("ITEM", item.getItemId() + "");
switch (item.getItemId()){
case R.id.nav_restaurant: {
//do stuff
}
case R.id.nav_pharmacy: {
//do stuff
}
case R.id.nav_bank: {
//do stuff
}
}
return false;
}
activity_maps.xml
<android.support.v4.widget.DrawerLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_height="match_parent"
android:layout_width="match_parent"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:id="#+id/drawer_layout">
<android.support.design.widget.NavigationView
android:layout_width="200dp"
android:layout_height="match_parent"
app:menu="#menu/navigation_menu"
android:id="#+id/navigation_menu"
android:layout_gravity="start"
app:headerLayout="#layout/navigation_header">
</android.support.design.widget.NavigationView>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Main Layout"
android:layout_gravity="center"
android:textAlignment="center"
android:textSize="30dp"/>
</LinearLayout>
<fragment
xmlns:map="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/map"
android:name="com.google.android.gms.maps.SupportMapFragment"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.example.damia.placefinder.activities.MapsActivity" />
The navigation menu opens and closes perfectly fine, and even closes once I select an item, but neither the two logs or the toast appears, showing that the onNavigationItemSelected was never called.
I suspect it has something to do with everything (the maps and nagivation drawer) being in the same activity but I'm not sure.
Because your NavigationView was covered by your LinearLayout and fragment. Please put the sequence of your views in activity_maps.xml in this way:
<DrawerLayout >
<LinearLayout />
<fragment />
<NavigationView /> <!-- on the top of views -->
</DrawerLayout>
And DO NOT FORGET return true; in your listener.

ViewPager + TabLayout with NavigationDrawer in every Activity - Issue

I encountered a problem that I didn't managed to solve: I have a MainActivity where there's a NavigationDrawer that allows me to go to three different activities. Those extend the MainActivity so I get the Drawer in every activity.
In the same MainActivity, I put a TabLayout with three tab Fragments.
The problem I'm facing is that whenever I go to one of the three activity from the drawer layout, I don't get the layout xml attached to Activity1 but instead I get again the TabLayout with the Fragments.
How can I solve this?
The result should look like Google Play app.
Here's my MainActivity:
public class MainActivity extends AppCompatActivity {
DrawerLayout mDrawerLayout;
ListView mDrawerList;
ActionBarDrawerToggle mDrawerToggle;
CollectionPagerAdapter mCollectionPagerAdapter;
ViewPager mViewPager;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar_layout);
TextView mTitle = (TextView) toolbar.findViewById(R.id.toolbar_title);
mTitle.setText(R.string.app_name);
setSupportActionBar(toolbar);
assert getSupportActionBar() != null;
this.getSupportActionBar().setDisplayShowTitleEnabled(false);
getWindow().addFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN);
mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer);
Button button1 = (Button)findViewById(R.id.button1); //this is inside the drawer layout
button1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(MainActivity.this, Activity1.class);
startActivity(intent);
}
});
mDrawerToggle = new ActionBarDrawerToggle(this,
mDrawerLayout,
null,
R.string.drawer_open,
R.string.drawer_close) {
public void onDrawerClosed(View v) {
super.onDrawerClosed(v);
invalidateOptionsMenu();
syncState();
}
public void onDrawerOpened(View v) {
super.onDrawerOpened(v);
invalidateOptionsMenu();
syncState();
}
};
mDrawerLayout.addDrawerListener(mDrawerToggle);
mDrawerToggle.setDrawerIndicatorEnabled(false);
mDrawerToggle.syncState();
mCollectionPagerAdapter = new CollectionPagerAdapter(
getSupportFragmentManager());
mViewPager = (ViewPager) findViewById(R.id.pager);
mViewPager.setAdapter(mCollectionPagerAdapter);
TabLayout tabs = (TabLayout)findViewById(R.id.tabs);
tabs.setupWithViewPager(mViewPager);
}
public class CollectionPagerAdapter extends FragmentPagerAdapter {
//final int NUM_ITEMS = 3; // number of tabs
public CollectionPagerAdapter(FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int position)
{
switch (position) {
case 0:
return new Tab1();
case 1:
return new Tab2();
case 2:
return new Tab3();
}
return null;
}
#Override
public int getCount()
{
return 3;
}
#Override
public CharSequence getPageTitle(int position) {
switch (position)
{
case 0:
return getString(R.string.tab1);
case 1:
return getString(R.string.tab2);
case 2:
return getString(R.string.tab3);
}
return null;
}
}
#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) {
switch (item.getItemId()) {
case android.R.id.home: {
if (mDrawerLayout.isDrawerOpen(mDrawerList)) {
mDrawerLayout.closeDrawer(mDrawerList);
} else {
mDrawerLayout.openDrawer(mDrawerList);
}
return true;
}
default:
return super.onOptionsItemSelected(item);
}
}
Activity1:
public class Activity1 extends MainActivity { //extends MainActivity
#Override
protected void onCreate(Bundle savedInstanceState) {
setContentView(R.layout.classe1); //setContentView before super.onCreate(savedInstanceState) allows me to get drawer in each activity
super.onCreate(savedInstanceState);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar_layout);
TextView mTitle = (TextView) toolbar.findViewById(R.id.toolbar_title);
mTitle.setText("Activity 1");
setSupportActionBar(toolbar);
assert getSupportActionBar() != null;
this.getSupportActionBar().setDisplayShowTitleEnabled(false);
getWindow().addFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN);
}
Tab1 (Fragment):
public class Tab1 extends Fragment {
View view;
public Tab1() {
}
#SuppressLint("InflateParams")
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
view = inflater.inflate(R.layout.tab1, null);
return view;
}
and my activity_main.xml:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
android:layout_height="match_parent"
android:layout_width="match_parent">
<android.support.v4.view.ViewPager
android:layout_height="match_parent"
android:layout_width="match_parent"
android:layout_marginBottom="60dp"
android:id="#+id/pager">
<ScrollView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:scrollbars="none"
android:overScrollMode="never">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
android:paddingBottom="#dimen/activity_vertical_margin"
android:orientation="vertical">
</LinearLayout>
</ScrollView>
</android.support.v4.view.ViewPager>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:gravity="bottom">
<android.support.design.widget.TabLayout
android:layout_width="match_parent"
android:layout_height="30dp"
android:id="#+id/tabs"
app:tabMode="scrollable"
app:tabSelectedTextColor="#color/colorPrimaryDark"
app:tabTextColor="#color/tab_text"
app:tabIndicatorColor="#android:color/transparent"
app:tabBackground="#drawable/selected_tab_color"
style="#style/MyCustomTabLayout"/>
<include layout="#layout/toolbar" android:id="#+id/toolbar_layout"/>
</LinearLayout>
</RelativeLayout>
<LinearLayout
android:id="#+id/linearLayout"
android:layout_width="304dp"
android:layout_height="match_parent"
android:layout_gravity="start"
android:clickable="true"
android:background="#ffffff">
<ScrollView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:scrollbars="none">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical">
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/uno"
android:text="Button to Activity1"/>
</LinearLayout>
</ScrollView>
</LinearLayout>
classe1.xml:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_height="match_parent"
android:layout_width="match_parent">
<FrameLayout
android:layout_height="match_parent"
android:layout_width="match_parent"
android:layout_marginBottom="30dp"
android:id="#+id/content_frame">
<ScrollView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:scrollbars="none"
android:overScrollMode="never">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
android:paddingBottom="#dimen/activity_vertical_margin"
android:orientation="vertical">
<TextView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:text="CLASSE 1"
android:textSize="35sp"
android:gravity="center"/>
</LinearLayout>
</ScrollView>
</FrameLayout>
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:gravity="bottom">
<include layout="#layout/toolbar" android:id="#+id/toolbar_layout"/>
</RelativeLayout>
</RelativeLayout>
Your problem is that the super.onCreate() call in Activity1 is calling setContentView() again in MainActivity, which is completely replacing Activity1's layout set with its call to setContentView().
Since you want tabs in MainActivity but not the other Activities, your other Activities shouldn't extend MainActivity. Instead, you should create a base Activity with the DrawerLayout that all of your Activities extend, including MainActivity, and then add whichever Views you need in the individual subclasses.
In the base Activity, we'll override the setContentView() method to first set the base layout, setup the drawer and toggle, and then inflate the subclass's layout into the DrawerLayout's content View. Note that we do not call setContentView() in the base Activity's onCreate() method.
public abstract class BaseActivity extends AppCompatActivity {
protected Toolbar toolbar;
protected DrawerLayout mDrawerLayout;
protected ActionBarDrawerToggle mDrawerToggle;
protected TextView mTitle;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
...
}
#Override
public void setContentView(int layoutResID) {
super.setContentView(R.layout.activity_base);
toolbar = (Toolbar) findViewById(R.id.toolbar_layout);
mTitle = (TextView) toolbar.findViewById(R.id.toolbar_title);
mTitle.setText(R.string.app_name);
setSupportActionBar(toolbar);
getSupportActionBar().setDisplayShowTitleEnabled(false);
getWindow().addFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN);
//this is inside the drawer layout
Button button1 = (Button)findViewById(R.id.button1);
button1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(BaseActivity.this, Activity1.class);
startActivity(intent);
}
});
mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
mDrawerToggle = new ActionBarDrawerToggle(this,
mDrawerLayout,
null,
R.string.drawer_open,
R.string.drawer_close) {
public void onDrawerClosed(View v) {
super.onDrawerClosed(v);
invalidateOptionsMenu();
syncState();
}
public void onDrawerOpened(View v) {
super.onDrawerOpened(v);
invalidateOptionsMenu();
syncState();
}
};
mDrawerLayout.addDrawerListener(mDrawerToggle);
mDrawerToggle.setDrawerIndicatorEnabled(false);
mDrawerToggle.syncState();
getLayoutInflater().inflate(layoutResID,
(ViewGroup) findViewById(R.id.content));
}
}
The base layout is pretty much the same, except everything specific to MainActivity is removed.
<android.support.v4.widget.DrawerLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/drawer_layout"
android:layout_width="match_parent"
android:layout_height="match_parent">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<FrameLayout android:id="#+id/content"
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="1" />
<include layout="#layout/toolbar" android:id="#+id/toolbar_layout"/>
</LinearLayout>
<LinearLayout
android:id="#+id/linearLayout"
android:layout_width="304dp"
android:layout_height="match_parent"
android:layout_gravity="start"
android:clickable="true"
android:background="#ffffff">
<ScrollView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:scrollbars="none">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical">
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/button1"
android:text="Button to Activity1"/>
</LinearLayout>
</ScrollView>
</LinearLayout>
</android.support.v4.widget.DrawerLayout>
In MainActivity, we no longer need to setup the drawer and toggle.
public class MainActivity extends BaseActivity {
private CollectionPagerAdapter mCollectionPagerAdapter;
private ViewPager mViewPager;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mCollectionPagerAdapter = new CollectionPagerAdapter(
getSupportFragmentManager());
mViewPager = (ViewPager) findViewById(R.id.pager);
mViewPager.setAdapter(mCollectionPagerAdapter);
TabLayout tabs = (TabLayout)findViewById(R.id.tabs);
tabs.setupWithViewPager(mViewPager);
}
...
}
And the layout for MainActivity is now basically just the ViewPager and TabLayout.
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<android.support.v4.view.ViewPager
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="1"
android:id="#+id/pager">
...
</android.support.v4.view.ViewPager>
<android.support.design.widget.TabLayout
android:layout_width="match_parent"
android:layout_height="30dp"
android:id="#+id/tabs"
app:tabMode="scrollable"
app:tabSelectedTextColor="#color/colorPrimaryDark"
app:tabTextColor="#color/tab_text"
app:tabIndicatorColor="#android:color/transparent"
app:tabBackground="#drawable/selected_tab_color"
style="#style/MyCustomTabLayout" />
</LinearLayout>
Then, to accomplish everything in Activity1 that your posted code is doing, all we need is this, since the Toolbar and title TextView are now in BaseActivity.:
public class Activity1 extends BaseActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.classe1);
mTitle.setText("Activity 1");
}
}
And the layout for Activity1 can be pared down significantly:
<ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:scrollbars="none"
android:overScrollMode="never">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
android:paddingBottom="#dimen/activity_vertical_margin"
android:orientation="vertical">
<TextView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:text="CLASSE 1"
android:textSize="35sp"
android:gravity="center"/>
</LinearLayout>
</ScrollView>
You call setContentView two times in the Activity1 onCreate method, the first time with R.layout.classe1 and the second time with R.layout.activity_main (when you call the super.onCreate). The last setContentView wins, your problem is here.

Categories

Resources