从Fragment设置自定义ActionBar标题

时间:2022-12-04 23:44:29

In my Main FragmentActivity, I setup my custom ActionBar title like this:

在我的Main FragmentActivity中,我设置了我的自定义ActionBar标题,如下所示:

    LayoutInflater inflator = (LayoutInflater) this
            .getSystemService(Context.LAYOUT_INFLATER_SERVICE);
    View v = inflator.inflate(R.layout.custom_titlebar, null);

    TextView tv = (TextView) v.findViewById(R.id.title);
    Typeface tf = Typeface.createFromAsset(this.getAssets(),
            "fonts/capsuula.ttf");
    tv.setTypeface(tf);
    tv.setText(this.getTitle());

    actionBar.setCustomView(v);

This works perfect. However, once I open other Fragments, I want the title to change. I am not sure how to access the Main Activity to do this? In the past, I did this:

这很完美。但是,一旦我打开其他片段,我希望标题发生变化。我不知道如何访问主要活动来执行此操作?在过去,我这样做:

((MainFragmentActivity) getActivity()).getSupportActionBar().setTitle(
            catTitle);

Can someone advise on the proper method?

有人可以建议正确的方法吗?

XML:

XML:

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="@android:color/transparent" >

    <TextView
        android:id="@+id/title"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerVertical="true"
        android:layout_marginLeft="5dp"
        android:ellipsize="end"
        android:maxLines="1"
        android:text=""
        android:textColor="#fff"
        android:textSize="25sp" />

</RelativeLayout>

18 个解决方案

#1


58  

In your activity:

在您的活动中:

public void setActionBarTitle(String title) {
    getSupportActionBar().setTitle(title);
}

And in your fragment:

在你的片段中:

public View onCreateView(LayoutInflater inflater, ViewGroup container,
        Bundle savedInstanceState) {

    // Set title bar
    ((MainFragmentActivity) getActivity())
            .setActionBarTitle("Your title");

}

===Update April, 10, 2015===

=== 2015年4月10日更新===

You should use listener to update your action bar title

您应该使用监听器来更新操作栏标题

Fragment:

分段:

public class UpdateActionBarTitleFragment extends Fragment {
private OnFragmentInteractionListener mListener;

public UpdateActionBarTitleFragment() {
}

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    if (getArguments() != null) {
    }
}

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {
    if (mListener != null) {
        mListener.onFragmentInteraction("Custom Title");
    }
    return inflater.inflate(R.layout.fragment_update_action_bar_title2, container, false);
}

@Override
public void onAttach(Activity activity) {
    super.onAttach(activity);
    try {
        mListener = (OnFragmentInteractionListener) activity;
    } catch (ClassCastException e) {
        throw new ClassCastException(activity.toString()
                + " must implement OnFragmentInteractionListener");
    }
}

@Override
public void onDetach() {
    super.onDetach();
    mListener = null;
}

public interface OnFragmentInteractionListener {
    public void onFragmentInteraction(String title);
}

}

}

And Activity:

和活动:

public class UpdateActionBarTitleActivity extends ActionBarActivity implements UpdateActionBarTitleFragment.OnFragmentInteractionListener {

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_update_action_bar_title);
}

@Override
public void onFragmentInteraction(String title) {
    getSupportActionBar().setTitle(title);
}

}

}

Read more here: https://developer.android.com/training/basics/fragments/communicating.html

在此处阅读更多内容:https://developer.android.com/training/basics/fragments/communicating.html

#2


143  

What you're doing is correct. Fragments don't have access to the ActionBar APIs, so you have to call getActivity. Unless your Fragment is a static inner class, in which case you should create a WeakReference to the parent and call Activity.getActionBar from there.

你正在做的是正确的。片段无法访问ActionBar API,因此您必须调用getActivity。除非你的Fragment是静态内部类,否则你应该为父类创建一个WeakReference并从那里调用Activity.getActionBar。

To set the title for your ActionBar, while using a custom layout, in your Fragment you'll need to call getActivity().setTitle(YOUR_TITLE).

要设置ActionBar的标题,在使用自定义布局时,在片段中,您需要调用getActivity()。setTitle(YOUR_TITLE)。

The reason you call setTitle is because you're calling getTitle as the title of your ActionBar. getTitle returns the title for that Activity.

你调用setTitle的原因是你将getTitle作为ActionBar的标题。 getTitle返回该Activity的标题。

If you don't want to get call getTitle, then you'll need to create a public method that sets the text of your TextView in the Activity that hosts the Fragment.

如果您不想调用getTitle,那么您需要创建一个公共方法,在托管Fragment的Activity中设置TextView的文本。

In your Activity:

在您的活动中:

public void setActionBarTitle(String title){
    YOUR_CUSTOM_ACTION_BAR_TITLE.setText(title);
}

In your Fragment:

在你的片段中:

((MainFragmentActivity) getActivity()).setActionBarTitle(YOUR_TITLE);

Docs:

文档:

Activity.getTitle

Activity.getTitle

Activity.setTitle

Activity.setTitle

Also, you don't need to call this.whatever in the code you provided, just a tip.

此外,您不需要调用此方法。无论您提供的代码是什么,只需提示。

#3


24  

Google examples tend to use this within the fragments.

谷歌的例子倾向于在片段中使用它。

private ActionBar getActionBar() {
    return ((ActionBarActivity) getActivity()).getSupportActionBar();
}

The fragment will belong to an ActionBarActivity and that is where the reference to the actionbar is. This is cleaner because the fragment doesn't need to know exactly what activity it is, it only needs to belong to an activity that implements ActionBarActivity. This makes the fragment more flexible and can be added to multiple activities like they are meant to.

该片段将属于ActionBarActivity,这是对操作栏的引用。这是更清晰的,因为片段不需要确切地知道它是什么活动,它只需要属于实现ActionBarActivity的活动。这使得片段更加灵活,可以像往常一样添加到多个活动中。

Now, all you need to do in the fragment is.

现在,你需要在片段中做的就是。

getActionBar().setTitle("Your Title");

This works well if you have a base fragment that your fragments inherit from instead of the normal fragment class.

如果您有一个片段继承而不是正常片段类的基本片段,这种方法很有效。

public abstract class BaseFragment extends Fragment {
    public ActionBar getActionBar() {
        return ((ActionBarActivity) getActivity()).getSupportActionBar();
    }
}

Then in your fragment.

然后在你的片段中。

public class YourFragment extends BaseFragment {
    @Override
    public void onActivityCreated(Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        getActionBar().setTitle("Your Title");
    }
}

#4


6  

Setting Activity’s title from a Fragment messes up responsibility levels. Fragment is contained within an Activity, so this is the Activity, which should set its own title according to the type of the Fragment for example.

从片段设置活动的标题会扰乱责任级别。片段包含在一个Activity中,因此这是Activity,它应该根据片段的类型设置自己的标题。

Suppose you have an interface:

假设你有一个界面:

interface TopLevelFragment
{
    String getTitle();
}

The Fragments which can influence the Activity’s title then implement this interface. While in the hosting activity you write:

可以影响Activity的标题的Fragments然后实现这个接口。在您写的托管活动中:

@Override
protected void onCreate(Bundle savedInstanceState)
{
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    FragmentManager fm = getFragmentManager();
    fm.beginTransaction().add(0, new LoginFragment(), "login").commit();
}

@Override
public void onAttachFragment(Fragment fragment)
{
    super.onAttachFragment(fragment);

    if (fragment instanceof TopLevelFragment)
        setTitle(((TopLevelFragment) fragment).getTitle());
}

In this manner Activity is always in control what title to use, even if several TopLevelFragments are combined, which is quite possible on a tablet.

通过这种方式,即使将多个TopLevelFragments组合在一起,Activity也始终可以控制使用的标题,这在平板电脑上非常有用。

#5


5  

In the Fragment we can use like this, It's working fine for me.

在Fragment中我们可以这样使用,它对我来说很好用。

getActivity().getActionBar().setTitle("YOUR TITLE");

#6


3  

Just in case if you are having issues with the code, try putting getSupportActionBar().setTitle(title) inside onResume() of your fragment instead of onCreateView(...) i.e

如果您遇到代码问题,请尝试在您的片段的onResume()内部放置getSupportActionBar()。setTitle(title)而不是onCreateView(...),即

In MainActivity.java :

在MainActivity.java中:

public void setActionBarTitle(String title) {
    getSupportActionBar().setTitle(title);
}

In Fragment:

在片段中:

 @Override
 public void onResume(){
     super.onResume();
     ((MainActivity) getActivity()).setActionBarTitle("Your Title");
 }

#7


2  

Use the following:

使用以下内容:

getActivity().setTitle("YOUR_TITLE");

#8


1  

If you have a main activity with many fragments you put in, usually using the navigationDrawer. And you have an array of titles for yours fragments, when you press back, for them to change, put this in the main actity that hold the fragments

如果您有一个包含许多片段的主活动,通常使用navigationDrawer。并且你有一系列的标题为你的片段,当你按回来,让他们改变,把它放在保存片段的主要行为

@Override
     public void onBackPressed() {

    int T=getSupportFragmentManager().getBackStackEntryCount();
    if(T==1) { finish();}

    if(T>1) {
        int tr = Integer.parseInt(getSupportFragmentManager().getBackStackEntryAt(T-2).getName());
        setTitle(navMenuTitles[tr]);  super.onBackPressed();
      }

}

This assumes that for each fragment you give it a tag, usually somewhere when you add the fragments to the list of navigationDrawer, according to the position pressed on the list. So that position is what i capture on the tag:

这假设对于每个片段,您可以根据列表中按下的位置为它提供一个标记,通常是在将片段添加到navigationDrawer列表时的某个位置。所以这个位置是我在标签上捕获的:

    fragmentManager.beginTransaction().
replace(R.id.frame_container, fragment).addToBackStack(position).commit();

Now, the navMenuTitles is something you load on the onCreate

现在,navMenuTitles是你在onCreate上加载的东西

 // load slide menu items
        navMenuTitles = getResources().getStringArray(R.array.nav_drawer_items);

The array xml is an array type string resource on strings.xml

数组xml是strings.xml上的数组类型字符串资源

 <!-- Nav Drawer Menu Items -->
    <string-array name="nav_drawer_items">
        <item>Title one</item>
        <item>Title Two</item>
    </string-array>

#9


1  

Save ur Answer in String[] object and set it OnTabChange() in MainActivity as Belowwww

保存你在String []对象中的答案,并在MainActivity中将其设置为OnTabChange(),如下面的那样

String[] object = {"Fragment1","Fragment2","Fragment3"};

public void OnTabChange(String tabId)
{
int pos =mTabHost.getCurrentTab();     //To get tab position
 actionbar.setTitle(object.get(pos));
}


//Setting in View Pager
public void onPageSelected(int arg0) {
    mTabHost.setCurrentTab(arg0);
actionbar.setTitle(object.get(pos));
}

#10


1  

Here is my solution for setting the ActionBar title from fragments, when using NavigationDrawer. This solution uses an Interface so the fragments does not need to reference the parent Activity directly:

这是我在使用NavigationDrawer时从片段设置ActionBar标题的解决方案。此解决方案使用接口,因此片段不需要直接引用父Activity:

1) Create an Interface:

1)创建一个接口:

public interface ActionBarTitleSetter {
    public void setTitle(String title); 
}

2) In the Fragment's onAttach, cast the activity to the Interface type and call the SetActivityTitle method:

2)在Fragment的onAttach中,将活动强制转换为Interface类型并调用SetActivityTitle方法:

@Override 
public void onAttach(Activity activity) { 
    super.onAttach(activity);
    ((ActionBarTitleSetter) activity).setTitle(getString(R.string.title_bubbles_map)); 
}

3) In the activity, implement the ActionBarTitleSetter interface:

3)在活动中,实现ActionBarTitleSetter接口:

@Override 
public void setTitle(String title) { 
    mTitle = title; 
}

#11


1  

The downside to your approach of casting like so

像你这样的铸造方法的缺点

((MainFragmentActivity) getActivity()).getSupportActionBar().setTitle(
        catTitle);

is that your fragment is no longer reusable outside of MainActivityFragment. If you don't plan to use it outside of that activity, then there's no problem. A better approach would be conditionally set the title depending on the activity. So inside your fragment, you would write:

是你的片段不再可以在MainActivityFragment之外重复使用。如果您不打算在该活动之外使用它,那么没有问题。更好的方法是根据活动有条件地设置标题。所以在你的片段中,你会写:

if (getActivity() instanceof ActionBarActivity) {
    ((ActionBarActivity) getActivity()).getSupportActionBar().setTitle("Some Title");
}

#12


1  

if you are using android studio 1.4 stable template provided by google than simple you had to write following code in onNavigationItemSelected methode in which your related fragment calling if condition.

如果你使用谷歌提供的android studio 1.4稳定模板而不是简单你必须在onNavigationItemSelected方法中编写以下代码,其中你的相关片段调用条件。

 setTitle("YOUR FRAGMENT TITLE");

#13


1  

I don't think that the accepted answer is a perfect answer for it. Since all the activities that use

我不认为接受的答案是一个完美的答案。由于所有活动都使用

Toolbar

工具栏

are extended using

延长使用

AppCompatActivity

AppCompatActivity

, the fragments called from it can use the below mentioned code for changing the title.

,从它调用的片段可以使用下面提到的代码来更改标题。

((AppCompatActivity) context).getSupportActionBar().setTitle("Your Title");

#14


0  

Just to add onto the selected answer, you may also want to add a second method to your main activity. So you would end up with the following methods in your main activity:

只是要添加到选定的答案,您可能还想为主要活动添加第二种方法。因此,您最终会在主要活动中使用以下方法:

public void setActionBarTitle(String title) {
    getSupportActionBar().setTitle(title);
}

public void setActionBarTitle(int resourceId) {
    setActionBarTitle(getResources().getString(resourceId);
}

This will allow you set the title from both a String variable as well as a resource ID such as R.id.this_is_a_string from your strings.xml file. This will also work a little more like how getSupportActionBar().setTitle() works since it allows you to pass in a resource ID.

这将允许您从strings变量以及来自strings.xml文件的资源ID(如R.id.this_is_a_string)设置标题。这也可以像getSupportActionBar()。setTitle()一样工作,因为它允许您传入资源ID。

#15


0  

There are many ways as as outlined above. You can also do this in onNavigationDrawerSelected()in your DrawerActivity

如上所述,有许多方法。您也可以在DrawerActivity中的onNavigationDrawerSelected()中执行此操作

public void setTitle(final String title){
    ((TextView)findViewById(R.id.toolbar_title)).setText(title);
}

@Override
public void onNavigationDrawerItemSelected(int position) {
    // update the main content by replacing fragments
    fragment = null;
    String title = null;
    switch(position){

    case 0:
        fragment = new HomeFragment();
        title = "Home";
        break;
    case 1:
        fragment = new ProfileFragment();
        title = ("Find Work");
        break;
    ...
    }
    if (fragment != null){

        FragmentManager fragmentManager = getFragmentManager();
        fragmentManager
        .beginTransaction()
        .replace(R.id.container,
                fragment).commit();

        //The key is this line
        if (title != null && findViewById(R.id.toolbar_title)!= null ) setTitle(title);
    }
}

#16


0  

At least for me, there was an easy answer (after much digging around) to changing a tab title at runtime:

至少对我来说,在运行时更改选项卡标题有一个简单的答案(经过多次挖掘):

TabLayout tabLayout = (TabLayout) findViewById(R.id.tabs); tabLayout.getTabAt(MyTabPos).setText("My New Text");

TabLayout tabLayout =(TabLayout)findViewById(R.id.tabs); tabLayout.getTabAt(MyTabPos).setText(“我的新文本”);

#17


0  

If you're using ViewPager (like my case) you can use:

如果您正在使用ViewPager(就像我的情况一样),您可以使用:

getSupportActionBar().setTitle(YOURE_TAB_BAR.getTabAt(position).getText());

in onPageSelected method of your VIEW_PAGER.addOnPageChangeListener

在VIEW_PAGER.addOnPageChangeListener的onPageSelected方法中

#18


0  

Best event for change title onCreateOptionsMenu

更改标题onCreateOptionsMenu的最佳活动

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {
    View view = inflater.inflate(R.layout.general, container,  
    setHasOptionsMenu(true); // <-Add this line
    return view;
}

@Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {

    // If use specific menu
    menu.clear();
    inflater.inflate(R.menu.path_list_menu, menu);
    // If use specific menu

    ((AppCompatActivity) getActivity()).getSupportActionBar().setTitle("Your Fragment");
    super.onCreateOptionsMenu(menu, inflater);
}

#1


58  

In your activity:

在您的活动中:

public void setActionBarTitle(String title) {
    getSupportActionBar().setTitle(title);
}

And in your fragment:

在你的片段中:

public View onCreateView(LayoutInflater inflater, ViewGroup container,
        Bundle savedInstanceState) {

    // Set title bar
    ((MainFragmentActivity) getActivity())
            .setActionBarTitle("Your title");

}

===Update April, 10, 2015===

=== 2015年4月10日更新===

You should use listener to update your action bar title

您应该使用监听器来更新操作栏标题

Fragment:

分段:

public class UpdateActionBarTitleFragment extends Fragment {
private OnFragmentInteractionListener mListener;

public UpdateActionBarTitleFragment() {
}

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    if (getArguments() != null) {
    }
}

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {
    if (mListener != null) {
        mListener.onFragmentInteraction("Custom Title");
    }
    return inflater.inflate(R.layout.fragment_update_action_bar_title2, container, false);
}

@Override
public void onAttach(Activity activity) {
    super.onAttach(activity);
    try {
        mListener = (OnFragmentInteractionListener) activity;
    } catch (ClassCastException e) {
        throw new ClassCastException(activity.toString()
                + " must implement OnFragmentInteractionListener");
    }
}

@Override
public void onDetach() {
    super.onDetach();
    mListener = null;
}

public interface OnFragmentInteractionListener {
    public void onFragmentInteraction(String title);
}

}

}

And Activity:

和活动:

public class UpdateActionBarTitleActivity extends ActionBarActivity implements UpdateActionBarTitleFragment.OnFragmentInteractionListener {

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_update_action_bar_title);
}

@Override
public void onFragmentInteraction(String title) {
    getSupportActionBar().setTitle(title);
}

}

}

Read more here: https://developer.android.com/training/basics/fragments/communicating.html

在此处阅读更多内容:https://developer.android.com/training/basics/fragments/communicating.html

#2


143  

What you're doing is correct. Fragments don't have access to the ActionBar APIs, so you have to call getActivity. Unless your Fragment is a static inner class, in which case you should create a WeakReference to the parent and call Activity.getActionBar from there.

你正在做的是正确的。片段无法访问ActionBar API,因此您必须调用getActivity。除非你的Fragment是静态内部类,否则你应该为父类创建一个WeakReference并从那里调用Activity.getActionBar。

To set the title for your ActionBar, while using a custom layout, in your Fragment you'll need to call getActivity().setTitle(YOUR_TITLE).

要设置ActionBar的标题,在使用自定义布局时,在片段中,您需要调用getActivity()。setTitle(YOUR_TITLE)。

The reason you call setTitle is because you're calling getTitle as the title of your ActionBar. getTitle returns the title for that Activity.

你调用setTitle的原因是你将getTitle作为ActionBar的标题。 getTitle返回该Activity的标题。

If you don't want to get call getTitle, then you'll need to create a public method that sets the text of your TextView in the Activity that hosts the Fragment.

如果您不想调用getTitle,那么您需要创建一个公共方法,在托管Fragment的Activity中设置TextView的文本。

In your Activity:

在您的活动中:

public void setActionBarTitle(String title){
    YOUR_CUSTOM_ACTION_BAR_TITLE.setText(title);
}

In your Fragment:

在你的片段中:

((MainFragmentActivity) getActivity()).setActionBarTitle(YOUR_TITLE);

Docs:

文档:

Activity.getTitle

Activity.getTitle

Activity.setTitle

Activity.setTitle

Also, you don't need to call this.whatever in the code you provided, just a tip.

此外,您不需要调用此方法。无论您提供的代码是什么,只需提示。

#3


24  

Google examples tend to use this within the fragments.

谷歌的例子倾向于在片段中使用它。

private ActionBar getActionBar() {
    return ((ActionBarActivity) getActivity()).getSupportActionBar();
}

The fragment will belong to an ActionBarActivity and that is where the reference to the actionbar is. This is cleaner because the fragment doesn't need to know exactly what activity it is, it only needs to belong to an activity that implements ActionBarActivity. This makes the fragment more flexible and can be added to multiple activities like they are meant to.

该片段将属于ActionBarActivity,这是对操作栏的引用。这是更清晰的,因为片段不需要确切地知道它是什么活动,它只需要属于实现ActionBarActivity的活动。这使得片段更加灵活,可以像往常一样添加到多个活动中。

Now, all you need to do in the fragment is.

现在,你需要在片段中做的就是。

getActionBar().setTitle("Your Title");

This works well if you have a base fragment that your fragments inherit from instead of the normal fragment class.

如果您有一个片段继承而不是正常片段类的基本片段,这种方法很有效。

public abstract class BaseFragment extends Fragment {
    public ActionBar getActionBar() {
        return ((ActionBarActivity) getActivity()).getSupportActionBar();
    }
}

Then in your fragment.

然后在你的片段中。

public class YourFragment extends BaseFragment {
    @Override
    public void onActivityCreated(Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        getActionBar().setTitle("Your Title");
    }
}

#4


6  

Setting Activity’s title from a Fragment messes up responsibility levels. Fragment is contained within an Activity, so this is the Activity, which should set its own title according to the type of the Fragment for example.

从片段设置活动的标题会扰乱责任级别。片段包含在一个Activity中,因此这是Activity,它应该根据片段的类型设置自己的标题。

Suppose you have an interface:

假设你有一个界面:

interface TopLevelFragment
{
    String getTitle();
}

The Fragments which can influence the Activity’s title then implement this interface. While in the hosting activity you write:

可以影响Activity的标题的Fragments然后实现这个接口。在您写的托管活动中:

@Override
protected void onCreate(Bundle savedInstanceState)
{
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    FragmentManager fm = getFragmentManager();
    fm.beginTransaction().add(0, new LoginFragment(), "login").commit();
}

@Override
public void onAttachFragment(Fragment fragment)
{
    super.onAttachFragment(fragment);

    if (fragment instanceof TopLevelFragment)
        setTitle(((TopLevelFragment) fragment).getTitle());
}

In this manner Activity is always in control what title to use, even if several TopLevelFragments are combined, which is quite possible on a tablet.

通过这种方式,即使将多个TopLevelFragments组合在一起,Activity也始终可以控制使用的标题,这在平板电脑上非常有用。

#5


5  

In the Fragment we can use like this, It's working fine for me.

在Fragment中我们可以这样使用,它对我来说很好用。

getActivity().getActionBar().setTitle("YOUR TITLE");

#6


3  

Just in case if you are having issues with the code, try putting getSupportActionBar().setTitle(title) inside onResume() of your fragment instead of onCreateView(...) i.e

如果您遇到代码问题,请尝试在您的片段的onResume()内部放置getSupportActionBar()。setTitle(title)而不是onCreateView(...),即

In MainActivity.java :

在MainActivity.java中:

public void setActionBarTitle(String title) {
    getSupportActionBar().setTitle(title);
}

In Fragment:

在片段中:

 @Override
 public void onResume(){
     super.onResume();
     ((MainActivity) getActivity()).setActionBarTitle("Your Title");
 }

#7


2  

Use the following:

使用以下内容:

getActivity().setTitle("YOUR_TITLE");

#8


1  

If you have a main activity with many fragments you put in, usually using the navigationDrawer. And you have an array of titles for yours fragments, when you press back, for them to change, put this in the main actity that hold the fragments

如果您有一个包含许多片段的主活动,通常使用navigationDrawer。并且你有一系列的标题为你的片段,当你按回来,让他们改变,把它放在保存片段的主要行为

@Override
     public void onBackPressed() {

    int T=getSupportFragmentManager().getBackStackEntryCount();
    if(T==1) { finish();}

    if(T>1) {
        int tr = Integer.parseInt(getSupportFragmentManager().getBackStackEntryAt(T-2).getName());
        setTitle(navMenuTitles[tr]);  super.onBackPressed();
      }

}

This assumes that for each fragment you give it a tag, usually somewhere when you add the fragments to the list of navigationDrawer, according to the position pressed on the list. So that position is what i capture on the tag:

这假设对于每个片段,您可以根据列表中按下的位置为它提供一个标记,通常是在将片段添加到navigationDrawer列表时的某个位置。所以这个位置是我在标签上捕获的:

    fragmentManager.beginTransaction().
replace(R.id.frame_container, fragment).addToBackStack(position).commit();

Now, the navMenuTitles is something you load on the onCreate

现在,navMenuTitles是你在onCreate上加载的东西

 // load slide menu items
        navMenuTitles = getResources().getStringArray(R.array.nav_drawer_items);

The array xml is an array type string resource on strings.xml

数组xml是strings.xml上的数组类型字符串资源

 <!-- Nav Drawer Menu Items -->
    <string-array name="nav_drawer_items">
        <item>Title one</item>
        <item>Title Two</item>
    </string-array>

#9


1  

Save ur Answer in String[] object and set it OnTabChange() in MainActivity as Belowwww

保存你在String []对象中的答案,并在MainActivity中将其设置为OnTabChange(),如下面的那样

String[] object = {"Fragment1","Fragment2","Fragment3"};

public void OnTabChange(String tabId)
{
int pos =mTabHost.getCurrentTab();     //To get tab position
 actionbar.setTitle(object.get(pos));
}


//Setting in View Pager
public void onPageSelected(int arg0) {
    mTabHost.setCurrentTab(arg0);
actionbar.setTitle(object.get(pos));
}

#10


1  

Here is my solution for setting the ActionBar title from fragments, when using NavigationDrawer. This solution uses an Interface so the fragments does not need to reference the parent Activity directly:

这是我在使用NavigationDrawer时从片段设置ActionBar标题的解决方案。此解决方案使用接口,因此片段不需要直接引用父Activity:

1) Create an Interface:

1)创建一个接口:

public interface ActionBarTitleSetter {
    public void setTitle(String title); 
}

2) In the Fragment's onAttach, cast the activity to the Interface type and call the SetActivityTitle method:

2)在Fragment的onAttach中,将活动强制转换为Interface类型并调用SetActivityTitle方法:

@Override 
public void onAttach(Activity activity) { 
    super.onAttach(activity);
    ((ActionBarTitleSetter) activity).setTitle(getString(R.string.title_bubbles_map)); 
}

3) In the activity, implement the ActionBarTitleSetter interface:

3)在活动中,实现ActionBarTitleSetter接口:

@Override 
public void setTitle(String title) { 
    mTitle = title; 
}

#11


1  

The downside to your approach of casting like so

像你这样的铸造方法的缺点

((MainFragmentActivity) getActivity()).getSupportActionBar().setTitle(
        catTitle);

is that your fragment is no longer reusable outside of MainActivityFragment. If you don't plan to use it outside of that activity, then there's no problem. A better approach would be conditionally set the title depending on the activity. So inside your fragment, you would write:

是你的片段不再可以在MainActivityFragment之外重复使用。如果您不打算在该活动之外使用它,那么没有问题。更好的方法是根据活动有条件地设置标题。所以在你的片段中,你会写:

if (getActivity() instanceof ActionBarActivity) {
    ((ActionBarActivity) getActivity()).getSupportActionBar().setTitle("Some Title");
}

#12


1  

if you are using android studio 1.4 stable template provided by google than simple you had to write following code in onNavigationItemSelected methode in which your related fragment calling if condition.

如果你使用谷歌提供的android studio 1.4稳定模板而不是简单你必须在onNavigationItemSelected方法中编写以下代码,其中你的相关片段调用条件。

 setTitle("YOUR FRAGMENT TITLE");

#13


1  

I don't think that the accepted answer is a perfect answer for it. Since all the activities that use

我不认为接受的答案是一个完美的答案。由于所有活动都使用

Toolbar

工具栏

are extended using

延长使用

AppCompatActivity

AppCompatActivity

, the fragments called from it can use the below mentioned code for changing the title.

,从它调用的片段可以使用下面提到的代码来更改标题。

((AppCompatActivity) context).getSupportActionBar().setTitle("Your Title");

#14


0  

Just to add onto the selected answer, you may also want to add a second method to your main activity. So you would end up with the following methods in your main activity:

只是要添加到选定的答案,您可能还想为主要活动添加第二种方法。因此,您最终会在主要活动中使用以下方法:

public void setActionBarTitle(String title) {
    getSupportActionBar().setTitle(title);
}

public void setActionBarTitle(int resourceId) {
    setActionBarTitle(getResources().getString(resourceId);
}

This will allow you set the title from both a String variable as well as a resource ID such as R.id.this_is_a_string from your strings.xml file. This will also work a little more like how getSupportActionBar().setTitle() works since it allows you to pass in a resource ID.

这将允许您从strings变量以及来自strings.xml文件的资源ID(如R.id.this_is_a_string)设置标题。这也可以像getSupportActionBar()。setTitle()一样工作,因为它允许您传入资源ID。

#15


0  

There are many ways as as outlined above. You can also do this in onNavigationDrawerSelected()in your DrawerActivity

如上所述,有许多方法。您也可以在DrawerActivity中的onNavigationDrawerSelected()中执行此操作

public void setTitle(final String title){
    ((TextView)findViewById(R.id.toolbar_title)).setText(title);
}

@Override
public void onNavigationDrawerItemSelected(int position) {
    // update the main content by replacing fragments
    fragment = null;
    String title = null;
    switch(position){

    case 0:
        fragment = new HomeFragment();
        title = "Home";
        break;
    case 1:
        fragment = new ProfileFragment();
        title = ("Find Work");
        break;
    ...
    }
    if (fragment != null){

        FragmentManager fragmentManager = getFragmentManager();
        fragmentManager
        .beginTransaction()
        .replace(R.id.container,
                fragment).commit();

        //The key is this line
        if (title != null && findViewById(R.id.toolbar_title)!= null ) setTitle(title);
    }
}

#16


0  

At least for me, there was an easy answer (after much digging around) to changing a tab title at runtime:

至少对我来说,在运行时更改选项卡标题有一个简单的答案(经过多次挖掘):

TabLayout tabLayout = (TabLayout) findViewById(R.id.tabs); tabLayout.getTabAt(MyTabPos).setText("My New Text");

TabLayout tabLayout =(TabLayout)findViewById(R.id.tabs); tabLayout.getTabAt(MyTabPos).setText(“我的新文本”);

#17


0  

If you're using ViewPager (like my case) you can use:

如果您正在使用ViewPager(就像我的情况一样),您可以使用:

getSupportActionBar().setTitle(YOURE_TAB_BAR.getTabAt(position).getText());

in onPageSelected method of your VIEW_PAGER.addOnPageChangeListener

在VIEW_PAGER.addOnPageChangeListener的onPageSelected方法中

#18


0  

Best event for change title onCreateOptionsMenu

更改标题onCreateOptionsMenu的最佳活动

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {
    View view = inflater.inflate(R.layout.general, container,  
    setHasOptionsMenu(true); // <-Add this line
    return view;
}

@Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {

    // If use specific menu
    menu.clear();
    inflater.inflate(R.menu.path_list_menu, menu);
    // If use specific menu

    ((AppCompatActivity) getActivity()).getSupportActionBar().setTitle("Your Fragment");
    super.onCreateOptionsMenu(menu, inflater);
}