How to change the text on the action bar

前端 未结 18 748
春和景丽
春和景丽 2020-11-22 12:30

Currently it just displays the name of the application and I want it to display something custom and be different for each screen in my app.

For example: my home scr

相关标签:
18条回答
  • 2020-11-22 13:25

    You just add this code in the onCreate method.

    setTitle("new title");
    
    0 讨论(0)
  • 2020-11-22 13:28

    try do this...

    public void onCreate(Bundle savedInstanceState) 
    {
    super.onCreate(savedInstanceState);
        this.setTitle(String.format(your_format_string, your_personal_text_to_display));
        setContentView(R.layout.your_layout);
           ...
           ...
    }
    

    it works for me

    0 讨论(0)
  • 2020-11-22 13:28
    ActionBar ab = getActionBar();
    TextView tv = new TextView(getApplicationContext());
    
    LayoutParams lp = new RelativeLayout.LayoutParams(
            LayoutParams.MATCH_PARENT, // Width of TextView
            LayoutParams.WRAP_CONTENT);
    tv.setLayoutParams(lp);
    tv.setTextColor(Color.RED);
    ab.setCustomView(tv);
    

    For more information check this link :

    http://android--code.blogspot.in/2015/09/android-how-to-change-actionbar-title_21.html

    0 讨论(0)
  • 2020-11-22 13:29

    Inside Activity.onCreate() callback or in the another place where you need to change title:

    getSupportActionBar().setTitle("Whatever title");
    
    0 讨论(0)
  • 2020-11-22 13:32

    You can define the label for each activity in your manifest file.

    A normal definition of a activity looks like this:

    <activity
         android:name=".ui.myactivity"
         android:label="@string/Title Text" />
    

    Where title text should be replaced by the id of a string resource for this activity.

    You can also set the title text from code if you want to set it dynamically.

    setTitle(address.getCity());
    

    with this line the title is set to the city of a specific adress in the oncreate method of my activity.

    0 讨论(0)
  • 2020-11-22 13:36

    For future developers that are using AndroidX and the navigation architectural component.

    Instead of setting the toolbar title using one of the solutions above, which can be very painful if you want to set it dynamically on a back stack change, you can set a placeholder for the title of the fragment in the navigation graph like the following:

    <fragment
        android:id="@+id/some_fragment"
        android:name="package.SomeFragment"
        android:label="Hello {placeholder}"
        tools:layout="@layout/fragment_some">
        <argument
            android:name="placeholder"
            app:argType="string" />
    </fragment>
    

    The placeholder value has to be provided using the FragmentDirections (via the action method).

    It is then replaced in the title and show like Hello World (when placeholder = "World").

    0 讨论(0)
提交回复
热议问题