Spinner in the toolbar appears when I search - Android Lollipop - android

I have a drawer navigation and I switch between fragments, in the Fragment ONE I have a spinner in the toolbar. In the Fragment TWO, I don't want the spinner, so I remove the spinner with the property "visibility=GONE" and that works.
BUT, in the Fragment TWO, doing the following steps, something strange really happens
Tap in the search icon
The search view appears in the toolbar
I tap cancel
The search view collapse, and the spinner from the Fragment ONE shows up
I have tried to use this listener "OnActionExpandListener" in the search icon to hide the spinner again when user taps cancel, but it doesn't work.
any ideas?
Drawer navigation where I set up the toolbar
<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"
android:fitsSystemWindows="true">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
>
<include layout="#layout/toolbar_dropdown"/>
<!-- The main content view -->
<FrameLayout
android:id="#+id/content_frame"
android:layout_width="match_parent"
android:layout_height="match_parent"
/>
</LinearLayout>
<!-- The navigation drawer -->
<ListView android:id="#+id/left_drawer"
android:fitsSystemWindows="true"
android:layout_width="240dp"
android:layout_height="match_parent"
android:layout_gravity="start"
android:layout_marginTop="56dp"
android:choiceMode="singleChoice"
android:divider="#color/gray_light_divider_list_drawerNav"
android:dividerHeight="1dp"
android:background="#color/gray_light_background_list_drawerNav"
/>
Drawer navigation Activity method OnCreate, where I setup the the toolbar
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
if (toolbar != null) {
setSupportActionBar(toolbar);
}
if(getSupportActionBar()!=null) {
getSupportActionBar().setDisplayShowTitleEnabled(false);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setHomeButtonEnabled(true);
}
This is how I switch between fragments
android.support.v4.app.FragmentTransaction transaction = fragmentManager.beginTransaction();
transaction.replace(R.id.content_frame, fragment);
transaction.addToBackStack(null);
transaction.commit();
Using the ActionBarDrawerToggle in the method onDrawerOpened, I remove the spinner, so that means that every time the Drawer Navigation is open I removed the spinner like this
Spinner spinner = (Spinner)findViewById(R.id.spinner_nav);
spinner.setVisibility(View.GONE);
This is the OnActionExpandListener in the Fragment TWO
MenuItemCompat.OnActionExpandListener searchOnActionExpandListener = new MenuItemCompat.OnActionExpandListener()
{
#Override
public boolean onMenuItemActionExpand(MenuItem menuItem) {
return true;
}
#Override
public boolean onMenuItemActionCollapse(MenuItem menuItem) {
Spinner spinner = (Spinner)findViewById(R.id.spinner_nav);
spinner.setVisibility(View.GONE);
return true;
}
};

To resolve this issue, I did the following.
I removed the spinner in the toolbar so it looks like this
<android.support.v7.widget.Toolbar
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:id="#+id/toolbar"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:minHeight="?attr/actionBarSize"
app:theme="#style/ThemeOverlay.AppCompat.Dark.ActionBar"
app:popupTheme="#style/ThemeOverlay.AppCompat.Light"
android:background="?attr/colorPrimary">
</android.support.v7.widget.Toolbar>
And I started to add the spinner in the fragment ONE programatically
Toolbar toolbar = (Toolbar)getActivity().findViewById(R.id.toolbar);
if(toolbar.findViewWithTag("spinner_nav")==null) {
Spinner spinner = new Spinner(getActivity());
spinner.setTag("spinner_nav");
//Setting up the adapter
AdapterFragmentOne spinnerAdapter = new AdapterFragmentOne(getActivity(), array);
spinnerAdapter.setDropDownViewResource(R.layout.spinner_dropdown_item);
if (spinner != null) {
spinner.setVisibility(View.VISIBLE);
spinner.setAdapter(spinnerAdapter);
}
spinnerAdapter.notifyDataSetChanged();
spinner.setOnItemSelectedListener(mOnNavigationListener);
toolbar.addView(spinner);
}
In my Drawer navigation Activity I remove the spinner when the drawer is opened, I execute
//Removing the spinner view
Spinner spinner = (Spinner) toolbar.findViewWithTag("spinner_nav");
toolbar.removeView(spinner);

Related

How to fix overlapping of previous fragment's collapsing toolbar and current fragment's content?

I'm new to android, and want to find solution for the following situation:
I have implemented fragment called profile, In which I have collapsing toolbar and TabLayout. Whenever I clicked on any of the button of current fragment, It will display next page as a new fragment accordingly.Next fragment have it's own toolbar.
Problem: Whenever I scroll the content, previous fragment Collapsing Toolbar appears on top. It overlaps the current fragment.
I have tried the solution using Framelayout and "fitSystemWindows = true".Another solution I have tried is giving "clickable=true" to next fragment. None of them helped me. Where I made a mistake?
Here's the overview of my code:
ProfileFragment is loaded from MainActivity which has bottom navigation view.
private BottomNavigationView.OnNavigationItemSelectedListener mOnNavigationItemSelectedListener
= new BottomNavigationView.OnNavigationItemSelectedListener() {
#Override
public boolean onNavigationItemSelected(#NonNull MenuItem item) {
switch (item.getItemId()) {
case R.id.navigation_profile:
ProfileFragment f5=new ProfileFragment();
FragmentTransaction ft5= getSupportFragmentManager().beginTransaction();
ft5.replace(R.id.fragment_container,f5,"");
ft5.commit();
return true;
}
return false;
}
};
activity_main.xml
<LinearLayout
android:id="#+id/container"
tools:context="com.work.workapp.MainActivity">
<FrameLayout
android:id="#+id/fragment_container">
</FrameLayout>
<android.support.design.widget.BottomNavigationView/>
</LinearLayout>
profile_fragment.xml
<android.support.design.widget.CoordinatorLayout
android:id="#+id/profile_main">
<android.support.design.widget.AppBarLayout
android:fitsSystemWindows="true">
<android.support.design.widget.CollapsingToolbarLayout
android:fitsSystemWindows="true"
app:layout_scrollFlags="scroll|exitUntilCollapsed">
<LinearLayout
android:fitsSystemWindows="true"
app:layout_collapseMode="parallax">
<ImageView/>
<TextView/>
</LinearLayout>
<android.support.v7.widget.Toolbar>
<RelativeLayout>
<!-- Settings Button -->
<!-- Edit Button -->
</RelativeLayout>
</android.support.v7.widget.Toolbar>
</android.support.design.widget.CollapsingToolbarLayout>
<android.support.design.widget.TabLayout/>
</android.support.design.widget.AppBarLayout>
<android.support.v4.view.ViewPager
app:layout_behavior="#string/appbar_scrolling_view_behavior"/>
<FrameLayout
android:id="#+id/container_profile"
android:layout_width="match_parent"
android:layout_height="match_parent"/>
</android.support.design.widget.CoordinatorLayout>
profile-toolbar
collapse toolbar - Tab post
tab_post and tab_work Adapter files:
/* Button click event from post Tab of tablayout*/
myViewHolder.button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
RequestsFragment req_list = new RequestsFragment();
FragmentTransaction ft = ((FragmentActivity)mContext).getSupportFragmentManager().beginTransaction();
ft.replace(R.id.container_profile, req_list, "");
ft.addToBackStack(null).commit();
}
});
When Click on "5" - button on Post tab, following fragment displayed:
Button click on Post tab
When scroll on above fragment, previous fragment's collapsed toolbar appears on new fragment:
content and toolbar overlaps
No error message appears. App is successfully running. I want to remove this Overlapping.

How to handle drawer toggle and toolbar up when having toolbar for each fragment

I am using single activity and many fragments approach in my app
Now since in my some fragments I have custom view in toolbar I decided to have separate toolbar for each fragment.
How to implement separate toolbar for each fragment also the drawer layout is in my activity
I have the same problem, I will add custom toolbar view for each fragment.
My Utility method is:
public static View addRemoveViewFromToolbar(FragmentActivity fragmentActivity, int resourceId) {
Toolbar toolbar = removeViewFromToolbar(fragmentActivity);
if (resourceId == 0) {
return null;
} else {
View view = LayoutInflater.from(fragmentActivity).inflate(resourceId, toolbar, false);
toolbar.addView(view);
return view;
}
}
public static Toolbar removeViewFromToolbar(FragmentActivity fragmentActivity) {
Toolbar toolbar = (Toolbar) fragmentActivity.findViewById(R.id.toolbar);
if (toolbar.getChildCount() > 1) {
for (int i = 1; i <= toolbar.getChildCount(); i++) {
toolbar.removeViewAt(1);
}
}
return toolbar;
}
In my each fragment
//Create your custom view based on requirement
View view = Utility.addRemoveViewFromToolbar(getActivity(), R.layout.toolbar_search_view);
if (view != null) {
edtCategory1 = (EditText) view.findViewById(R.id.edtCategory1);
edtCategory1.setOnClickListener(this);
}
Hope this explanation help you :)
I'm not sure if I understood your description of the your app correctly, but I recently did what I think you described.
My activity layout was a DrawerLayout with an included CoordinatorLayout/AppBar layout with a single toolbar and a FrameLayout below. The menu.xml contained all the items I needed in my toolbar for all the fragments. Items clicked in the nav menu would swap out fragments in the FrameLayout. My onNavigationItemSelected() called on this method to swap out the fragments and handle the backstack:
public void switchView(int id, int optArg) {
if (currentView != id) {
currentView = id; //currentView keeps track of which fragment is loaded
FragmentTransaction transaction = getFragmentManager().beginTransaction();
//Fragment contentFragment is the current fragment in the FrameLayout
switch (id) {
case 0: //menu item 1
contentFragment = new Nav_Item1_Fragment();
transaction.replace(R.id.fragment_container, contentFragment, "");
break;
case 1: //menu item 2
contentFragment = new Nav_Item2_Fragment();
transaction.replace(R.id.fragment_container, contentFragment, "");
break;
case 2: //menu item 3
contentFragment = new Nav_Item3_Fragment();
transaction.replace(R.id.fragment_container, contentFragment, "");
break;
}
// Replace whatever is in the fragment_container view with this fragment,
// and add the transaction to the back stack
// transaction.replace(R.id.fragment_container, contentFragment);
transaction.addToBackStack(null);
// Commit the transaction
transaction.commit();
}
}
and in each fragment's onPrepareOptionsMenu() I setVisible() hid/showed the menu items in the toolbar related to that fragment. Each item had an method in the activity pointed to by the menu item's onClick attribute that knew what fragment it was from and what views were passed to it.
The drawer was setup in the onCreate() of the activity with a ActionBarDrawerToggle like so:
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.addDrawerListener(toggle);
toggle.syncState();
activity xml:
<android.support.v4.widget.DrawerLayout
android:id="#+id/drawer_layout"
...>
<include
layout="#layout/app_bar_main"
android:layout_width="match_parent"
android:layout_height="match_parent"/>
<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"
.../>
</android.support.v4.widget.DrawerLayout>
app_bar_main.xml
<?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.support.design.widget.AppBarLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
...>
<android.support.v7.widget.Toolbar
android:id="#+id/toolbar"
android:layout_width="match_parent"
android:layout_height="?attr/actionBarSize"
android:gravity="top"
.../>
</android.support.design.widget.AppBarLayout>
<FrameLayout
android:id="#+id/fragment_container"
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
app:layout_behavior="#string/appbar_scrolling_view_behavior">
</FrameLayout>
</android.support.design.widget.CoordinatorLayout>
So...One Nav menu, one App/Tool Bar, multiple fragments
Why do you specifically want a separate toolbar for each fragment?
You can easily change the toolbar view for each fragment.
In your function to switch fragments -
public void selectDrawerItem(MenuItem item) {
FragmentManager fragmentManager = getSupportFragmentManager();
FragmentTransaction fragmentTransaction;
switch (item.getItemId()) {
case R.id.nav_home :
getSupportActionBar().setCustomView(R.layout.home_nav_bar);
fragmentClass = HomeFragment.class;
break;
case R.id.nav_settings :
getSupportActionBar().setCustomView(R.layout.settings_nav_bar);
fragmentClass = SettingsFragment.class;
break;
}
fragment = (Fragment) fragmentClass.newInstance();
fragmentManager.popBackStack(null,
FragmentManager.POP_BACK_STACK_INCLUSIVE);
fragmentTransaction = fragmentManager.beginTransaction();
fragmentTransaction.replace(R.id.fragment_container, fragment);
fragmentTransaction.addToBackStack(null);
fragmentTransaction.commit();
}
So you can easily use the same toolbar and customize it according to your requirements for each fragment.
It can be done in a quite straightforward way.
First create an activity with a drawerlayout.
Second create a container viewpager inside the activity to hold
the fragments
Third implement a listener on your viewpager that will set the
relevant toolbar based on the fragment on display.
Let me illustrate by relevant XMLs and code
First the Drawerlayout XML for the main activity
<?xml version="1.0" encoding="utf-8"?>
<android.support.v4.widget.DrawerLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/drawer_layout"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:fitsSystemWindows="true"
tools:openDrawer="start">
<include
layout="#layout/app_bar_landing_page"
android:layout_width="match_parent"
android:layout_height="match_parent" />
<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:headerLayout="#layout/nav_header_landing_page"
app:menu="#menu/activity_landing_page_drawer" />
</android.support.v4.widget.DrawerLayout>
Please note the container layout app_bar_landing_page. Now the XML for this
<?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"
tools:context="me.veganbuddy.veganbuddy.ui.LandingPage">
<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"
android:elevation="4dp"
app:logo="#drawable/vegan_buddy_menu_icon"
app:popupTheme="#style/AppTheme.PopupOverlay" />
</android.support.design.widget.AppBarLayout>
<android.support.v4.view.ViewPager
android:id="#+id/container_for_fragments"
android:layout_width="match_parent"
android:layout_height="match_parent"
app:layout_behavior="#string/appbar_scrolling_view_behavior" />
</android.support.design.widget.CoordinatorLayout>
Note the viewpager which will act as container for fragments. Now the OnPageChangeListener on the viewpager.
mViewPager = (ViewPager) findViewById(R.id.container_for_fragments);
mViewPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
#Override
public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
}
#Override
public void onPageSelected(int position) {
switch (position+1){
case 0:setSupportActionBar(aToolbar);
break;
case 1:setSupportActionBar(bToolbar);
break;
case 2:setSupportActionBar(cToolbar);;
break;
case 3:setSupportActionBar(dToolbar);
break;
default:
break;
}
}
Let me know if any further clarification is needed
The simplest approach I would suggest is to use callbacks to activity. Whenever each fragment loads in the activity, arrange a callback to the activity and load the appropriate toolbar in the activity.
Have separate toolbar xmls in your layout folder. Use the include tag to put the toolbars in your activity. Keep only 1 toolbar visible at a time. When the fragment callbacks come to your activity make the necessary one visible.
It's very simple. Besides the onclick action for the Category fragment is taking you into a new activity, not a Fragment. Now, since drawer layout is in parent activity with navigation view and without toolbar then in the first drawer fragment is a tablayout having four tabs with viewpager and a toolbar on the top and inside one tab i.e HOME is the TOP CHARTS, CATEGORIES, EDITORS. Each toolbar must be implemented in each fragment layout and not in the activity layout since you want different toolbars for each fragment. Note that Toolbar is not a property of Fragment but it's a property of ActionBarActivity or AppCompatActivity, then in the onCreateView, of the fragment that's holding the HOME, GAMES, MOVIES, MUSIC, put down these codes.
public class Drawer1Fragment extends Fragment{
public Drawer1Fragment () {}
TabLayout tabLayout;
Toolbar toolbar;
DrawerLayout drawerLayout;
ViewPager viewPager;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState){
View myChildRoot = inflater.inflate(R.layout.child_fragment_attachment, container, false);
tabLayout = myChildRoot.findViewById(R.id.tab_layout);
viewPager= myChildRoot.findViewById(R.id.container_viewPager);
toolbar = myChildRoot.findViewById(R.id.toolbar);
drawerLayout = getActivity().findViewById(R.id.drawer_layout);
((AppCompatActivity)requireActivity()).setSupportActionBar(toolbar);
((AppCompatActivity)requireActivity()).getSupportActionBar().setTitle(getActivity().getResources().getString(R.string.app_name));
((AppCompatActivity)requireActivity()).getSupportActionBar().setHomeButtonEnabled(true);
((AppCompatActivity)getParentFragment().requireActivity()).getSupportActionBar().setDisplayHomeAsUpEnabled(true);
ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(getActivity(),drawerLayout,toolbar,R.drawable.icons,R.string.app_name);
drawerLayout.addDrawerListener(toggle);
toggle.syncState();
// The back arrow of a toolbar in fragment is implemented below
toolbar.setNavigationOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view)
{
if(!drawerLayout.isDrawerOpen(GravityCompat.START)) {
drawerLayout.openDrawer(GravityCompat.START);
} else {
getActivity().finish();
}
}
});
return myChildRoot;
}
}

Toolbar not responding to Listview scroll events

I have an activity which contains a custom toolbar and a simple listview. I want the toolbar respond when the listview is scrolled. However, it is not working.
Here is the .xml file
<?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"
tools:context="com.abdralabs.talksee.HistoryActivity">
<android.support.design.widget.AppBarLayout
android:id="#+id/history_appbar"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:fitsSystemWindows="true"
android:theme="#style/ThemeOverlay.AppCompat.Dark.ActionBar">
<android.support.v7.widget.Toolbar
android:id="#+id/history_toolbar"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#color/title"
app:layout_scrollFlags="scroll|enterAlways">
</android.support.v7.widget.Toolbar>
</android.support.design.widget.AppBarLayout>
<ListView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/lv_history"
app:layout_behavior="#string/appbar_scrolling_view_behavior">
</ListView>
Here is the .java file
public class HistoryActivity extends AppCompatActivity {
Toolbar toolbar;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_history);
toolbar = (Toolbar)findViewById(R.id.history_toolbar);
/*
setSupportActionBar(toolbar);
getSupportActionBar().setHomeButtonEnabled(true);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
*/
toolbar.setTitle("History");
String[] rcArray = {"A","B","C","D","A","B","C","D","A","B","C","D","A","B","C","D","A","B","C","D","A","B","C","D","A","B","C","D"};
ArrayAdapter adapter = new ArrayAdapter<String>(this,
R.layout.list_history, rcArray);
ListView listView = (ListView) findViewById(R.id.lv_history);
listView.setAdapter(adapter);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
return super.onCreateOptionsMenu(menu);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
/*
switch (item.getItemId()){
case android.R.id.home:
NavUtils.navigateUpFromSameTask(this);
break;
}
*/
return super.onOptionsItemSelected(item);
}
}
What have I done wrong?
EDIT:
In response to rafsanahmad007's answer
I have applied the changes as per your suggestion but still there is no change.
When I scroll through the ListView there is no change to the size of the ToolBar. However, when I click on the ToolBar itself and make an up & down motion the ToolBar moves up & down too. What I want to achieve is, when I scroll the ListView downwards the ToolBar should collapse and when I scroll the ListView upwards the ToolBar should get to its normal size/position.
The following pictures depict how the ToolBar is responding currently.
As you can see in the above pics, the ListView is not being scrolled, but the ToolBar itself is being scrolled. What I want is, when I scroll the ListView the ToolBar should scroll only during that time. I hope I have clarified myself.
try this:
<android.support.design.widget.AppBarLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:fitsSystemWindows="true"
android:theme="#style/ThemeOverlay.AppCompat.Dark.ActionBar">
<android.support.v7.widget.Toolbar
android:id="#+id/toolbar"
android:layout_width="match_parent"
android:layout_height="?attr/actionBarSize"
android:minHeight="80dp"
app:layout_scrollFlags="scroll|enterAlwaysCollapsed" />
</android.support.design.widget.AppBarLayout>
you can also get Help from Here

How to add a back button to action bar / toolbar

I have written a piece of code as part of an app where I want to implement a back button on the action bar/tool bar such that when the button is pressed, the previous page (the page/fragment immediately before the current page/fragment) will be displayed.
This is the code for the ToolBar, DrawerLayout, NavigationView and getSupportActionBar():
final DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
final NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
android.support.v7.widget.Toolbar toolbar = (android.support.v7.widget.Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
toolbar.setVisibility(View.VISIBLE);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setLogo(R.mipmap.ic_launcher);
getSupportActionBar().setDisplayUseLogoEnabled(true);
getSupportActionBar().setHomeButtonEnabled(true);
I am unable to use ActionBar. For some reason (I don't know why), my Android studio/ program, will not allow me to use the ActionBar. So I am substituting that with the set/getSupportActionBar().
The function used in relation to this are:
#Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.menu_settings, menu);
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();
switch (id) {
case android.R.id.home:
onBackPressed();
return true;
default:
return super.onOptionsItemSelected(item);
}
}
#Override
public void onBackPressed() {
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
if (drawer.isDrawerOpen(GravityCompat.START)) {
drawer.closeDrawer(GravityCompat.START);
} else {
super.onBackPressed();
}
}
My activity_main.xml file is:
<?xml version="1.0" encoding="utf-8"?>
<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:fitsSystemWindows="true"
android:id="#+id/activity_main"
android:orientation="vertical"
tools:openDrawer="start"
tools:context="com.example.albin.settings_menu.SettingsActivity">
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#fff">
<android.support.v7.widget.Toolbar
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:id="#+id/toolbar"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="?attr/colorPrimary"
app:popupTheme="#style/ThemeOverlay.AppCompat.Dark.ActionBar"
app:title="Settings"/>
<android.support.v4.widget.DrawerLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/drawer_layout"
android:layout_width="match_parent"
android:layout_height="match_parent">
<FrameLayout
android:id="#+id/frame"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="#+id/toolbar">
</FrameLayout>
<android.support.design.widget.NavigationView
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:id="#+id/nav_view"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:layout_gravity="start"
android:fitsSystemWindows="true"
android:layout_marginTop="-24dp"
app:menu="#menu/options_menu" />
</android.support.v4.widget.DrawerLayout>
</RelativeLayout>
</LinearLayout>
The problem is that I don't know which is the useful code, which is the useless code and how to mix/join/(add additional codes to) these (codes, methods, variables/objects, fragments, xml layouts) to get the desired outcome, that is, the application of a back button on the action bar/tool bar.
Most of the code above is implemented for the up button, not the back button. I have read at several places that up and back buttons are not the same.
I tried several links on internet as well as on this site, but none of them has just what I need.
Hope someone can give me an clear answer...
You can include the back icon in ToolBar:
Initialize ToolBar:
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
You can use an drawable icon as a back button.
toolbar.setNavigationIcon(R.drawable.your_drawable_icon);
toolbar.setNavigationOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// what do you want here
}
});
If you do not want to use drawable icon then:
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setDisplayShowHomeEnabled(true);
toolbar.setNavigationOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// what do you want here
}
});
Actually your layout having that issue because you have added toolbar in RelativeLayout so drawer layout is overlapping on it that's why you would not able to click on back arrow, i have fix your layout see below
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:id="#+id/activity_main"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:fitsSystemWindows="true"
android:orientation="vertical">
<android.support.v7.widget.Toolbar
android:id="#+id/toolbar"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="?attr/colorPrimary"
app:navigationIcon="#drawable/ic_back_black"
app:popupTheme="#style/ThemeOverlay.AppCompat.Dark.ActionBar"
app:title="Settings" />
<android.support.v4.widget.DrawerLayout
android:id="#+id/drawer_layout"
android:layout_width="match_parent"
android:layout_height="match_parent">
<FrameLayout
android:id="#+id/frame"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="#+id/toolbar" />
<android.support.design.widget.NavigationView
android:id="#+id/nav_view"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_gravity="start"
android:fitsSystemWindows="true"
app:menu="#menu/options_menu" />
</android.support.v4.widget.DrawerLayout>
</LinearLayout>
The simplest way would be to add parent activity in manifest file as developer docs suggest.
<activity
android:name=".ChildActivity"
android:parentActivityName=".ParentActivity" >
and java code you already have done it, setSupportActionbar and setHomeAsUpEnabled.
Edited :
its necessary to add up action for icon to be visible, as mentioned in
Android Developer Docs
So toolbar gives added flexibility to modify title-bar in Android.
As far as why getActionBar is not working and you are compelled to use getSupportActionBar is because you must be using SupportLibrary. SupportLibrary gives backward compatibility to earlier SDK versions.
If you want to modify your title-bar/header/action-bar extensively
then use toolbar otherwise use action-bar.
Add a navigation click listener to your toolbar , like below
toolbar.setNavigationOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
onBackPressed();
}
});
If you are referencing some actions from the action bar, such as a Save action or a Share one, and you are overriding onOptionsItemSelected method, then you need to define the behavior when the back or home button is clicked:
#Override public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.action_save:
//save stuff
break;
//this is what you need to add to reference again back/home button
case android.R.id.home:
//do your stuff here, usually back to the home or close the current activity
getActivity().finish();
break;
default:
break;
}
return true;

Navigation Menu in Support Action Bar not opening

EDIT: So the menu exists but I can only get to it by sliding the menu out, the button on the top left corner doesn't toggle the drawer open.
I'm trying to implement a nav menu but instead of a hamburger button showing that opens my menu, I'm left with a non-functioning back button. I'm assuming it's a little different than the Nav Button tutorial Google has due to using a toolbar as my action bar.
MainActivity.java:
private CharSequence mTitle;
private FragmentTabHost mTabHost;
private Toolbar toolbar;
private ListView mDrawerList;
private DrawerLayout mDrawerLayout;
FrameLayout frameLayout;
DrawerLayout Drawer; // Declaring DrawerLayout
ActionBarDrawerToggle mDrawerToggle; // Declaring Action Bar Drawer Toggle
String TITLES[];
int ICONS[] = {R.drawable.drawer_back, R.drawable.drawer_settings,R.drawable.drawer_notifications, R.drawable.drawer_feedback};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
TITLES = getResources().getStringArray(R.array.menu_array);
mTitle = getTitle();
toolbar = (Toolbar) findViewById(R.id.tool_bar); // Attaching the layout to the toolbar object
frameLayout = (FrameLayout) findViewById(R.id.frame_layout);
setSupportActionBar(toolbar);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setHomeButtonEnabled(true);
mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
mDrawerList = (ListView) findViewById(R.id.left_drawer);
mDrawerLayout.setDrawerShadow(R.drawable.drawer_shadow, GravityCompat.START);
mDrawerList.setAdapter(new ArrayAdapter<>(this,
R.layout.item_row, TITLES));
mDrawerList.setOnItemClickListener(new DrawerItemClickListener());
mDrawerToggle = new ActionBarDrawerToggle(this,Drawer,R.string.openDrawer,R.string.closeDrawer){
public void onDrawerClosed(View view) {
getSupportActionBar().setTitle(mTitle);
invalidateOptionsMenu(); // creates call to onPrepareOptionsMenu()
}
public void onDrawerOpened(View drawerView) {
getSupportActionBar().setTitle(mTitle);
invalidateOptionsMenu(); // creates call to onPrepareOptionsMenu()
}
};
}
main_activity.xml:
<android.support.v4.widget.DrawerLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/drawer_layout"
android:layout_width="match_parent"
android:layout_height="match_parent">
<FrameLayout 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:id="#+id/frame_layout"
tools:context=".MainActivity">
<include
android:id="#+id/tool_bar"
layout="#layout/tool_bar"
></include>
<include
android:id="#+id/gm_header"
layout="#layout/gm_header"
></include>
<!-- As the main content view, the view below consumes the entire
space available using match_parent in both dimensions. -->
<android.support.v4.app.FragmentTabHost
xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#android:id/tabhost"
android:layout_width="match_parent"
android:layout_height="match_parent">
<LinearLayout
android:id="#+id/LinearLayout01"
android:orientation="vertical"
android:layout_height="fill_parent"
android:layout_width="fill_parent">
<FrameLayout
android:id="#android:id/tabcontent"
android:layout_width="0dp"
android:layout_height="0dp"
android:layout_weight="0"/>
<FrameLayout
android:id="#+id/realtabcontent"
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="1"/>
<TabWidget
android:id="#android:id/tabs"
android:orientation="horizontal"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:paddingTop="10dp"
android:background="#color/ColorPrimaryDark"
android:layout_weight="0"/>
</LinearLayout>
</android.support.v4.app.FragmentTabHost>
</FrameLayout>
<ListView android:id="#+id/left_drawer"
android:layout_width="240dp"
android:layout_height="match_parent"
android:layout_gravity="start"
android:choiceMode="singleChoice"
android:divider="#android:color/transparent"
android:dividerHeight="0dp"
android:background="#111"/>
</android.support.v4.widget.DrawerLayout>
First, there's two DrawerLayouts declared, one called Drawer and one called mDrawerLayout. I'm going to use mDrawerLayout.
In the Drawer Toggle constructor, you can associate the toggle with the DrawerLayout and the Toolbar by declaring it with mDrawerToggle = new ActionBarDrawerToggle(this, mDrawerLayout, toolbar, R.string.openDrawer, R.string.closeDrawer){
// rest of code
Then add another couple of lines
If you want the icon to change between a hamburger and an arrow when the drawer opens and closes use this listener:
mDrawerLayout.setDrawerListener(mDrawerToggle);
call syncState to put the button and drawer into the same state(open or closed):
mDrawerToggle.syncState();
You can achieve proper "back" navigation by handling the click events of the menu items. The one you're talking about in Android is referred as the Up button which is known as the home menu item. Add this code to your Activity and you'll be able to go back from the current Activity to the previous one:
#Override
public boolean onOptionsItemSelected(MenuItem item) {
if (item.getItemId() == android.R.id.home) {
finish();
return true;
}
return super.onOptionsItemSelected(item);
}
Now there are way better ways to handle the UP navigation than this. This approach simply kills the current Activity you see which will end up behaving like a back navigation as you'd like to call it.
Please refer to this section from the Android documentation to understand what's the difference between
Back:
and Up:
Once you understand the difference, you can check out this section to understand how the proper Up navigation should be handled.
Cheers!

Categories

Resources