Getting Toolbar in Fragment - android

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.

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

Hide/Show Toolbar programmatically on CoordinatorLayout

When I scroll my RecycleView ToolBar hide or show (with animation).
How I can return ToolBar back programmatically?
If your toolbar is inside an AppBarLayout which is probably inside your CoordinatorLayout then something like this should work.
AppBarLayout appBarLayout = (AppBarLayout)findViewById(R.id.appBar);
appBarLayout.setExpanded(true, true);
Or to collapse it
AppBarLayout appBarLayout = (AppBarLayout)findViewById(R.id.appBar);
appBarLayout.setExpanded(false, true);
Here is the definition
setExpanded(boolean expanded, boolean animate)
Take note that this method is available from v23 of the support library, here is some documentation for reference, the key thing to note is "As with AppBarLayout's scrolling, this method relies on this layout being a direct child of a CoordinatorLayout."
Is that what you looking for?
Toolbar toolbar = findViewById(R.id.toolbar); // or however you need to do it for your code
AppBarLayout.LayoutParams params = (AppBarLayout.LayoutParams) toolbar.getLayoutParams();
params.setScrollFlags(0); // clear all scroll flags
link: How to enable/disable toolbar scrolling programmatically when using design support library
In order to hide the Toolbar your can just do something like this:
toolbar.animate().translationY(-toolbar.getBottom()).setInterpolator(new AccelerateInterpolator()).start();
If you want to show it again you call:
toolbar.animate().translationY(0).setInterpolator(new DecelerateInterpolator()).start();
My problem was very similar to #Artem I tried many fix but none of them worked for me. #Jraco11's answer is correct when you use AppBarLayout. #johnrao07 not worked for me. But I found a perfect solution for this problem when we use Toolbar.
To hide Toolbar programatically
if (toolbar.getParent() instanceof AppBarLayout){
((AppBarLayout)toolbar.getParent()).setExpanded(false,true);
}
To show Toolbar programatically
if (toolbar.getParent() instanceof AppBarLayout){
((AppBarLayout)toolbar.getParent()).setExpanded(true,true);
Refer original answer(answer by #Android HHT):- programmatically-show-toolbar-after-hidden-by-scrolling-android-design-library

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

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

Use DrawerLayout and FlyOutContainer

I have a problem, I would like to put in my Layout the Drawer Layout and the FlyOutContainer but in the error Log it shows an error:that DrawerLayout cannot be cast to FlyOutContainer what can I do to fix this problem. I need the Drawer Layout to go to the MainActivity.
Hope you can help me and sorry for my bad english.
The code in that demo inflates a layout and casts the root view of the Layout to FlyOutContainer. If you change your layout xml so that the root is now DrawerLayout, then that code no longer runs correctly and you are probably getting ClassCastException. You should do it this way instead (in onCreate()):
setContentView(R.layout.your_activity_layout);
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout_id);
FlyOutContainer flyOutContainner = (FlyOutContainer) findViewById(R.id.fly_out_container_id);
Of course, if you don't actually need a reference to these views/layouts, you can just stop after setContentView(...)

Categories

Resources