SupportActionBar:如何更改标题?

时间:2019-11-05 21:20:09

标签: android appbar

此布局来自Studio 3.5.1模板。我不知道。但我的问题希望有一个简单的答案。

这是XML布局:

    <?xml version="1.0" encoding="utf-8"?>
    <androidx.coordinatorlayout.widget.CoordinatorLayout xmlns:android="http://schemas.android.com/apk/res/android"
        xmlns:app="http://schemas.android.com/apk/res-auto"
        xmlns:tools="http://schemas.android.com/tools"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        tools:context=".ChecklistActivity">

        <androidx.viewpager.widget.ViewPager
            android:id="@+id/view_pager"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            app:layout_behavior="@string/appbar_scrolling_view_behavior" />

        <com.google.android.material.appbar.AppBarLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:id="@+id/tabAppBarLayout"
            android:theme="@style/AppTheme.AppBarOverlay">

            <com.google.android.material.tabs.TabLayout
                android:id="@+id/tabLayoutView"
                app:tabMode="scrollable"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:background="?attr/colorPrimary" />

        </com.google.android.material.appbar.AppBarLayout>

    </androidx.coordinatorlayout.widget.CoordinatorLayout>

在我的应用程序活动(Java)中,我想更改android:label="@string/app_name文本(在活动清单中指定),使其显示在活动标题(appBar,toolBar,无论它是什么)上。到目前为止,我还无法做到这一点。

Screenshot of AppBar with tilte

1 个答案:

答案 0 :(得分:2)

否,您不能按照清单名称那样在清单中添加或删除或更改任何内容,这是清单文件,系统在安装您的应用时会读取该文件。

如果您只是想更改标题,可以使用:

如果您使用的是ActionBar

getActionBar().setTitle(int titleId)

如果要扩展AppCompatActivity

getSupportActionBar().setTitle(int titleId)

例如:

public class ChecklistActivity extends AppCompatActivity {

    @Override 
    public void onCreate(...) {
        doMyTimerThing();
    }

    public void doMyTimerThing() {
       onTick(long timeLeft) {
           ...(long to string here)...
           getSupportActionBar().setTitle(timeToShowOnActionBar)
       }
    }
}

Set Up the app bar Android Dev Guide

ActionBar vs SupportActionBar

ActionBar Docs

这是一个简单的实现,如果您希望在应用程序进行过程中对ActionBar进行更多控制,则可以使用Toolbar。工具栏必须添加到您的XML。