Hi there I have been using the ViewPagerIndicator library for some time now and I want my action-bar's title to change every time the user swipes to another Fragment to the other pages here is the code I am thinking off but it is just not working.
Activity miz = getActivity();
miz.setTitle("Miz");
I have put this code in all my Fragments displaying different titles every time but for some reason it is not working properly as it is always late. I think it may have something to do with the OnCreate , OnResume or OnPause and can not lay a finger on it can some one help ? I want the Title of the Action Bar to change while the next Fragment is visible to the user.
I have also though of some code like this
#Override
public void onResume() {
// TODO Auto-generated method stub
super.onResume();
Activity miz = getActivity();
miz.setTitle("Miz");
}
Regular :
this.getActivity().getActionBar().setTitle(title);
With ActioBarSherlock :
this.getSherlockActivity().getSupportActionBar().setTitle(title);
You can do this:
ActionBar actionBar = getActionBar(); // or getSupportActionBar() for ActionBarSherlock
actionBar.setTitle("test");
In a Fragment:
ActionBar actionBar = getActivity().getActionBar();
actionBar.setTitle("test");
Try
((AppCompatActivity) getActivity()).getSupportActionBar().setTitle("Miz");
It will work
Reference: Setting a subtitle on my Toolbar from a fragment
Related
Is there any way to listen if actionbar is invisible or visible.(a callback/listener method). "isShowing()" not working in my cases.
My Case :
I've a YouTube player in full screen mode with overlaying an actionbar (android.support.v7.app.ActionBar) and a dialog fragment added at bottom of the screen. Now, I need a listener to hide and show that dialog fragment, but there have no such listener in youtube player api. So, I'm trying to get it through inheriting actionbar visibility. Unfortunately, I couldn't find a listener if actionbar is now Visible or Invisible.
Create two functions in activity
void showActionbar() { getSupportActionBar().show(); }
void hideActionbar() { getSupportActionBar().hide(); }
Call them in your fragment when you want to show or hide. Here is how you call
((ActivityName)getActivity()).showActionbar();
((ActivityName)getActivity()).hideActionbar();
You can also check if actionbar showing with
boolean IsActionbarVisible() { if(getSupportActionBar().isShowing())
return true; else return false; }
I have a Navigation Drawer in the main activity of my app. On the onCreate method of the activity I initialize one of the fragments like this :
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
if (savedInstanceState == null) {
MenuItem menuItem = navigationView.getMenu().findItem(R.id.menu_history);
openFragment(menuItem);
}
public void openFragment(MenuItem menuItem){
Fragment newFragment = null;
switch (menuItem.getItemId()){
case R.id.menu_history :
newFragment = new HistoryFragment();
break;
//.....
}
if (newFragment != null){
//Replace content frame in activity_main.xml with newFragment
getSupportFragmentManager().beginTransaction()
.replace(R.id.content_frame, newFragment)
.commit();
menuItem.setChecked(true);
getSupportActionBar().setTitle(menuItem.getTitle());
}
drawerLayout.closeDrawers();
}
This all works well, the fragment appears on startup with the title on the toolbar being "History". But when the app goes into onPause and then onResume the toolbar title switches from "History" to the app name. I suspect this is an issue with onResume not opening the fragment / returning to its previous state correctly, because when I added the following lines to onResume the issue stopped:
#Override
protected void onResume() {
super.onResume();
MenuItem menuItem = navigationView.getMenu().findItem(R.id.menu_history);
openFragment(menuItem);
}
That solution seems to fix it but that means it has to reload the fragment with the animations every time the app is resumed, which isn't optimal. Any ideas on how to fix this?
If it helps, to recreate the issue I found useful to make the app split screen, because it always calls onResume. Thanks.
Inside your openFragment() method, you write:
getSupportActionBar().setTitle(menuItem.getTitle());
This is the only thing that changes your toolbar's title.
Note that this code has nothing to do with your Fragments, per se. When your activity is destroyed and recreated, the active Fragment will be successfully (automatically) destroyed and recreated by the FragmentManager... but your openFragment() method won't run again and so nothing will update your toolbar's title.
There are numerous ways you could solve this. Probably the right thing to do is update your toolbar's title from within one of your Fragment's lifecycle methods.
Edit: A reasonable place to update your toolbar's title would be in your fragment's onActivityCreated() method. This will run both when the fragment is first added and during recreation. Something like:
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
((AppCompatActivity) getActivity()).getSupportActionBar().setTitle("hello world");
}
If you do not want to re-create the fragment each time, you should use saveInstanceState like mentioned here: https://stackoverflow.com/a/17135346/1505074
I would like that in each Fragment the title of the ActionBar will be adapted. For example, if I select the option "Lists" (that is a Fragment), the title of the ActionBar have to be "Lists".
I can do it using the following code:
getActivity().setTitle("Lists");
but when I go back to MainActivity (using the menu option or the back button on the mobile phone) it maintains the title "Lists" instead of "My application" that is the default title.
If I try to set the title on MainActivity:
setTitle("My application");
it is not changed.
How can I maintain the title of the MainActivity and modify the title in each of the Fragments?
Thanks in advance!
Finally I am able to modify the title of your MainActivity after enter in a Fragment and modify the title of the ActionBar in it. I needed to change it with two different events: when I click on the menu of the application and when I press back button of the mobile phone. I will separate my answer in two parts, one for each event:
- To change title on MainActivity when you press back button on your mobile phone
You need to use onBackPressed() method on your MainActivity.class to detect the event and then use setTitle method to change the title of your ActionBar.
#Override
public void onBackPressed() {
setTitle("Lists");
}
- To change title on MainActivity when you press option "Home" in your menu.
On your onNavigationItemSelected method you can detect when you press the option "Home" and then start a new Fragment (let's call it MainFragment) which returns an empty layout so if you are in another Fragment, for example AnotherFragment (with another ActionBar title) and you press your "Home" option in your menu you can set again the title of your MainActivity as default one in your MainFragment with the following code:
getActivity().setTitle("Lists");
In this way you will be able to change the title of your MainActivity maintaining its layout.
Try using getSupportActionBar().setTitle("title");
That's what I use and it seems to work good. Here's an example using my code where I add fragments to a viewpager.
private void addPages(ViewPager pager) {
MyFragPagerAdapter adapter = new MyFragPagerAdapter(getSupportFragmentManager());
Intent intent = getIntent();
String workout = intent.getStringExtra("work");
Bundle args = new Bundle();
args.putString("work", work);
String title = args.getString("work");
switch(title) {
case "w29w1" : {
getSupportActionBar().setTitle("Work 29 Week 1");
break;
}
case "w29w2" : {
getSupportActionBar().setTitle("Work 29 Week 2");
break;
}
MondayFragment mondayFragment = new MondayFragment();
mondayFragment.setArguments(args);
In that example, I'm simply setting the title of the toolbar to something, depending on the intent it got from the previous class, as the fragment is used for multiple sets of data.
Put this code on onResume() of both activity and Fragment
Fragment:
#Override
public void onResume() {
super.onResume();
if(getActivity().getSupportActionBar()!=null)
getActivity().getSupportActionBar().setTitle("Lists");
}
Activity:
#Override
protected void onResume() {
super.onResume();
if(getSupportActionBar()!=null)
getSupportActionBar().setTitle("Title");
}
I have this code in my Activity:
protected void onCreate(Bundle savedInstanceState) {
...
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
ActionBar actionBar = getSupportActionBar();
if (actionBar != null) {
actionBar.setDisplayHomeAsUpEnabled(true);
}
...
}
I'm updating the ActionBar title from various fragments like this in onResume():
ActionBar actionBar = ((AppCompatActivity) getActivity()).getSupportActionBar();
if (actionBar != null) {
actionBar.setTitle(title);
}
This is working fine, but after orientation change, the title changes to the app name again. How I can overcome this?
EDIT:
After investigating more, I tried this and found this weird behaviour:
Added this code where I was setting title in Fragments:
final ActionBar actionBar = ((AppCompatActivity)getActivity()).getSupportActionBar();
if (actionBar != null) {
new Handler().postDelayed(new Runnable() {
#Override
public void run() {
Log.d("SWAPNIL", "IN RUN BEFORE: " + actionBar.getTitle());
actionBar.setTitle(title);
Log.d("SWAPNIL", "IN RUN AFTER : " + actionBar.getTitle());
}
}, 3000);
}
And here's the log:
10-13 10:27:04.526 3719-3719/com.example.xxxx D/SWAPNIL: onResumeHelp
10-13 10:27:07.528 3719-3719/com.example.xxxx D/SWAPNIL: IN RUN BEFORE: MY APP NAME
10-13 10:27:07.528 3719-3719/com.example.xxxx D/SWAPNIL: IN RUN AFTER : title
10-13 10:27:21.012 3719-3719/com.example.xxxx D/SWAPNIL: onResumeHelp
10-13 10:27:24.013 3719-3719/com.example.xxxx D/SWAPNIL: IN RUN BEFORE: title
10-13 10:27:24.013 3719-3719/com.example.xxxx D/SWAPNIL: IN RUN AFTER : title
It was getting changed as per logs but wasn't reflected in UI.
Please help me!
Okay, finally, after spending 2 days on this silly thing, I got the solution (I would say workaround).
This is probably a nested Fragment bug.
I have nested Fragment structure. As we know Fragment.getActivity() returns parent Activity. After lot of debugging I observed that if you call getActivity() after orientation change (even inside Fragment.onActivityCreated()) it returns reference of the old Activity except in top most parent fragment where it correctly returns the newly created Activity.
So I've written this method to get current Activity from any Fragment:
/**
* When inside a nested fragment and Activity gets recreated due to reasons like orientation
* change, {#link android.support.v4.app.Fragment#getActivity()} returns old Activity but the top
* level parent fragment's {#link android.support.v4.app.Fragment#getActivity()} returns current,
* recreated Activity. Hence use this method in nested fragments instead of
* android.support.v4.app.Fragment#getActivity()
*
* #param fragment
* The current nested Fragment
*
* #return current Activity that fragment is hosted in
*/
public Activity getActivity(Fragment fragment) {
if (fragment == null) {
return null;
}
while (fragment.getParentFragment() != null) {
fragment = fragment.getParentFragment();
}
return fragment.getActivity();
}
You need to see the answer written by sorianiv here:
In android app Toolbar.setTitle method has no effect – application name is shown as title
Adding the additional toolbar.setTitle("") resolved this issue for me.
Toolbar toolbar = (Toolbar) root.findViewById(R.id.toolbar);
toolbar.setTitle("");
((AppCompatActivity)getActivity()).setSupportActionBar(toolbar);
toolbar.setTitle("Profiles");
I just ran into the same issue, and I solved it by using getSupportActionBar instead of toolbar.
getSupportActionBar().setTitle("...");
You're activity is getting recreated when you rotate the screen. So onCreate is getting called again, and you have not set a title there.
Add the following to your onCreate:
actionBar.setTile("Enter title here")
maybe you can change your Action Bar / ToolBar, in onPostCreate() method in your Activity..
The code is just simple. I try to change my emulator / device orientation for many times and it works like charm..
#Override
protected void onPostCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onPostCreate(savedInstanceState);
toolbar.setTitle(mTitle);
}
Add in Manifest file
<activity
android:name=".Activity"
android:configChanges="orientation|screenSize|keyboardHidden"/>
or
code in onConfigChange()
if(newConfig.orientation==Configuration.ORIENTATION_LANDSCAPE){
// Set Title for Landscape
}else{
// Set Title for Portrait
I'm trying to change the title of activity, where i'm going to the activity from the fragments, so when i click on the hardware back button the title doesn't chnage to the one that i have provided in that activity i.e
this.setTitle("Something");
I have also tried
setTitle("Something");
Update
When i use the below mentioned code i run into a problem where the title that i assign in the mainActivity stay in all the pages, hence in the frgament getActivity().setTitle(""); seems to be useless in this case, so instead of changing everywhere the title using the below mentioned code i.e changing the actionbar title using getsupportactionbar.settitle(""), is there an easy way to do.
By any means can i know if an activity has came from the system back button back state or not?
You can handle this situation with onResume() method
//...
#Override
onResume(){
super.onResume();
this.getActionBar().setTitle("Something");
}
ı think, that will help you.
Try this:
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
ActionBar ab = getActionBar();
ab.setTitle("My Title");
ab.setSubtitle("sub-title");
}
EDIT:
For SupportActionBar use:
ActionBar actionBar = getSupportActionBar();
EDIT2:
I use this to set Title from every fragment
#Override
public void onResume() {
super.onResume();
// Set the title
getActivity().getActionBar() //getSupportActionBar()
.setTitle(R.string.fragment_title);
}
If you always add your fragment to backstack when changing, then backpress can be override as follows to always get your previous fragment's title:
#Override
public void onBackPressed() {
int T= getFragmentManager().getBackStackEntryCount();
if (getFragmentManager().getBackStackEntryCount() == 0) {
finish();
}
else if (getFragmentManager().getBackStackEntryCount() == 1) {
finish();
}
else {
String tr = getFragmentManager().getBackStackEntryAt(T-2).getName();
setTitle(tr);
getFragmentManager().popBackStack();
}
}
If you are occured this in Kotlin just remove Label from destination in Your navigation graph.
getSupportActionbar().setTitle("Your Title")
You have to call this whenever you want to change your title.
If you are switching between fragments call the method again and switch it back to your old title.