How to implement the Toolbar in the default Navigation Drawer Activity? - android

I am using Android Studio 1.0.1. I created a new Navigation Drawer Activity that is by default provided by this IDE. It created 2 Java files -
HomePage.javathat extends android.support.v7.app.AndroidBarActivity
NavigationDrawerFragment that extends Fragment
Along with that it provided me with 3 layout files -
activity_home_page.xml
fragment_home_page.xml
fragment_navigation_drawer.xml
Now what I wanted to do was hide the Action Bar and instead get the Toolbar as I wanted to do some detailed designing. For that I took the following steps -
Created a new style in styles.xml
true
false
Changed the theme of the application in AndroidManifest.xml
android:theme="#style/AppTheme"
Created a toolbar layout and included it in activity_home_page.xml
Added a Toolbar object to HomePage.java
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar); setSupportActionBar(toolbar);
But unfortunately, my app force closes whenever I launch HomePage activity. Any suggestions?
Logcat
activity_home_page.xml
HomePage.java
NavigationDrawerFragment.java
custom_toolbar.xml

The problem:
In your fragment you have:
toolbar = (Toolbar) getActivity().findViewById(R.id.toolbar);
...
toolbar.getContext()
However when you call findViewById the activity has not yet called setContentView. That means toolbar was not yet inflated and toolbar is set to null. Therefore toolbar.getContext() throws an NPE.
Fix:
Instead of toolbar.getContext() simply call getActivity(), to get the context.
If your fragment really does need the toolbar, you should call it after your activity's onCreate. A good place for that is onActivityCreated:
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
toolbar = (Toolbar) getActivity().findViewById(R.id.toolbar);
}

Related

setTitle() behaves differently at different times

I'm extending AppCompatActivity and setting ActionBar using setSupportActionBar().
There's a bit of confusion in setting the title.
If I do -
Toolbar toolbar = (Toolbar) findViewById(R.id.titlebar);
setSupportActionBar(toolbar);
toolbar.setTitle("Title 1"); // Does not work
setTitle("Title 2"); // Works
getSupportActionBar().setTitle("Title 3"); // Works
setTitle("Title 4"); // Does not work. Why?
What I see is that getSupportActionBar().setTitle() is creating a new view for the title and then the activity is losing the reference to it.
Is this the intended behavior or a bug in Android?
If you call setSupportActionBar(Toolbar), then the Action Bar is then responsible for handling the title, therefore you need to call getSupportActionBar().setTitle("My Title"); to set a custom title.
Also check this link where toolbar.setTitle("My title"); may cause problem like below:- In android app Toolbar.setTitle method has no effect – application name is shown as title
And toolbar is the general form of action bar.
We can have multiple toolbars as layout widget but action is not.
Thus better approach is to use getSupportActionBar().setTitle("My Title");
copy this line
setSupportActionBar(toolbar);
add the end of your line.
Toolbar toolbar = (Toolbar) findViewById(R.id.titlebar);
setSupportActionBar(toolbar);
toolbar.setTitle("Title 1");
setTitle("Title 2");
getSupportActionBar().setTitle("Title 3");
setTitle("Title 4");
setSupportActionBar(toolbar);
It's an intended behaviour once your set setSupportActionBar(Toolbar). support library internal creates new view for display title.
setTitle() is method of Activity it'll update only title if used setActionBar(Toolbar). But, it doesn't have backward compatability.
Ref
AppCompatDelegateImplBase
AppCompatDelegateImplV9

Android - When to call method of Activity from Fragment

I have an Activity which has Toolbars. When I move to Fragment A, the Toolbar needs to be changed specifically for Fragment A.
Fragment A contains 4 other Fragments as A is a FragmentPager.
I called the method of the Activity like :
((NewsfeedActivity)getActivity()).changeTitleBesideIcon("Purchases");
((NewsfeedActivity)getActivity()).changeIcon(getResources().getDrawable(R.drawable.purchase));
((NewsfeedActivity)getActivity()).changeBackground(getResources().getColor(R.color.purpleC));
((NewsfeedActivity)getActivity()).hideToolbarBottomMarketplace();
Somehow, the icon doesn't get changed, BUT the title does, along with the color.. I even set the method to setVisibility(View.VISIBLE); on the icon..
Is there a specific state where that kind of method needs to be called? Or am I just doing it wrong?
Update
This is my changeIcon method
public void changeIcon(Drawable imageDrawable){
toolbarImage.setVisibility(View.GONE);
toolbarIcon.setVisibility(View.VISIBLE);
toolbarIcon.setImageDrawable(imageDrawable);
}
toolbarImage is an ImageView located in the Toolbar
This is how it is :
<Toolbar>
<RelativeLayout>
<ImageView> //Toolbar Image
<ImageView>// Toolbar Icon
</RelativeLayout>
</Toolbar>
And I'm calling the methods in the onCreateView()..
try it.
public void changeIconToolbar(int resId){
getSupportActionBar().setHomeAsUpIndicator(resId);
}
it work for me
Well, now I can see that you possibly use Toolbar (rather than ActionBar) and once again I assume that the Toolbar is the toolbar added in API level 21 rather than AppCompat Toolbar.
In order to use this toolbar, I assume that you have called setActionBar (toolbar) to replace the ActionBar with the toolbar from your layout.
NOTE: Without calling this setActionBar (toolbar), your activity will continue using the default ActionBar (in onCreate()) and nothing will be shown.
Now, when the toolbar is in its place. I think your code will work.
PS: I recommend to use AppCompat Toolbar

Getting Toolbar in Fragment

I set up a toolbar in my main activity and when I go inside a fragment, I want to add a slider on it. If I had had the access to the Toolbar object, I would simply do:
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
getSupportActionBar().setDisplayShowTitleEnabled(false);
Spinner mNavigationSpinner = new SpinnerTrigger(getSupportActionBar().getThemedContext());
toolbar.addView(mNavigationSpinner);
But if I get it using
((ActionBarActivity) getActivity()).getSupportActionBar()
I don't have any addView() method. So my question is, how can I add a view to the Toolbar in fragment if the Toolbar itself was created in an Activity.
I'm not sure if this is the best view of going about this, but I don't think I can have the Spinner in defined in the layout, because most of my fragments don't use it, they simply set a title to the toolbar. But at the same time, it would be great if I could define the toolbar once in the main activity and not redo it for every fragment.
Another way of achieving the same thing from Ellitz answer, inside the fragment access the toolbar (or any other view inside activity) directly:
Toolbar toolbar = (Toolbar) getActivity().findViewById(R.id.toolbar);
you can get it using
Toolbar refTool = ((NameOfClass)getActivity()).toolbar;
or, create an instance of your MainActivity, then, override onAttach(Activity activity) and assign your instance object of MainActivity to the activity in onAttach()
See toolbar main purpose is https://developer.android.com/reference/android/widget/Toolbar.html read here so there are nothing deference in toolbar and actionbar. so if you want to add view to toolbar before it set to Actionbar then toolbar.addView(your view); is fine but after apply apply to setactionbar(toolbar) or setSupportActionbar(toolbar) you can set view to actionbar.
ex. ((ActionBarActivity) getActivity()).getSupportActionBar().setView(Your view)
Thats it...
I would like to add a casting to what Budius said.
Toolbar toolbar = (Toolbar)getActivity().findViewById(R.id.toolbar);
is the right way of doing it. Because
getActivity().findViewById(R.id.toolbar);
returns a view. This will give you error and you should cast it to Toolbar.

Menu icons toolbar on Android 5.0 (Lollipop)

I can't load the menu items in the toolbar. I'm using the Drawer Navigation, and I can't even show the hamburger icon.
I'm using getSuportActionBar, my activity extends from ActionBarActivity, I added the toolbar xml into my activity xml.
SOLUTION
I found my solution here, I just added a LinearLayout as a parent in the toolbar
Appcompat Toolbar Not Showing With Navigation Drawer
You can set your favorite icon and add a listener.
mToolbar.setNavigationIcon(R.drawable.ic_drawer);
mToolbar.setNavigationOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
mDrawerLayout.openDrawer(Gravity.START);
}
});
I found my solution here, I just added a LinearLayout as a parent in the toolbar
Appcompat Toolbar Not Showing With Navigation Drawer

how to set NAVIGATION_MODE_LIST on Toolbar new appcompat v7 21

Now all methods related to navigation modes in the ActionBar class, such as setNavigationMode()... are now deprecated.
The documentation explains:
Action bar navigation modes are deprecated and not supported by inline toolbar action bars. Consider using other common navigation patterns instead.
In my current application, there is a spinner on ActionBar. How do I apply NAVIGATION_MODE_LIST on the new widget Toolbar in the new version appcompat v7 21.
Thanks in advance.
With the API 21 the method setNavigationMode(ActionBar.NAVIGATION_MODE_LIST) is deprecated.
The best way to work with a spinner is to use a Toolbar like this:
<android.support.v7.widget.Toolbar
android:id="#+id/toolbar_actionbar"
android:layout_height="?attr/actionBarSize"
android:layout_width="match_parent"
android:background="?attr/colorPrimary">
<Spinner
android:id="#+id/spinner_toolbar"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
</android.support.v7.widget.Toolbar>
You can find an example in the Google IO 2014
As usual Gabriele is right, so your code will look like that:
So It will look like something like that:
private ActionBar actionBar;
private Toolbar toolbar;
private Spinner spinner;
private List<String> mNavigationItems;
private ArrayAdapter<CharSequence> mArrayAdapter;
/***
* Boolean to know which version is running
*/
private boolean postICS,postLollipop;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_nav_list);//find the toolbar
toolbar = (Toolbar) findViewById(R.id.toolbar);
postLollipop =getResources().getBoolean(R.bool.postLollipop);
if(postLollipop){
toolbar.setElevation(15);
}
//define the toolbar as the ActionBar
setSupportActionBar(toolbar);
actionBar=getSupportActionBar();
//now manage the spinner
mNavigationItems=new ArrayList<String>();
mNavigationItems.add("navigation 1");
mNavigationItems.add("nav 2");
mNavigationItems.add("navigation 3");
spinner= (Spinner) findViewById(R.id.action_bar_spinner);
mArrayAdapter = new ArrayAdapter(this, R.layout.actionbar_spinner_dropdown_item, mNavigationItems);
mArrayAdapter.setDropDownViewResource(R.layout.actionbar_spinner_dropdown_item);
spinner.setAdapter(mArrayAdapter);
}
And take care not to use spinnerAdapter (because you won't be able to manage its style using the AppTheme).
And if you want to use Tab (NavigationMode.Tabs) you should use now the Design library (explained here:http://android-developers.blogspot.fr/2015/05/android-design-support-library.html?m=1)and copy paste below
"
Tabs Switching between different views in your app via tabs is not a
new concept to material design and they are equally at home as a top
level navigation pattern or for organizing different groupings of
content within your app (say, different genres of music).
The Design library’s TabLayout implements both fixed tabs, where the
view’s width is divided equally between all of the tabs, as well as
scrollable tabs, where the tabs are not a uniform size and can scroll
horizontally. Tabs can be added programmatically:
TabLayout tabLayout = ...;
tabLayout.addTab(tabLayout.newTab().setText("Tab 1")); However, if you
are using a ViewPager for horizontal paging between tabs, you can
create tabs directly from your PagerAdapter’s getPageTitle() and then
connect the two together using setupWithViewPager(). This ensures that
tab selection events update the ViewPager and page changes update the
selected tab.
"

Categories

Resources