目前它只显示应用程序的名称,我希望它显示一些自定义的东西,在我的应用程序中的每个屏幕都是不同的。

例如:我的主屏幕可以在操作栏中显示“page1”,而应用程序切换到的另一个活动可以在该屏幕操作栏中显示“page2”。


当前回答

科特林

您可以以这种方式在Kotlin中以编程方式完成它。如果"supportActionBar"为空,你就忽略它:

    supportActionBar?.setTitle(R.string.my_text)
    supportActionBar?.title = "My text"

或者这样。如果“supportActionBar”为空,则抛出异常。

    supportActionBar!!.setTitle(R.string.my_text)
    supportActionBar!!.title = "My text"

其他回答

我们可以用以下两种方式之一更改动作栏标题:

In the Manifest: in the manifest file, set the label of each Activity. android:label="@string/TitleWhichYouWantToDisplay" In code: in code, call the setTitle() method with a String or the id of String as the argument. public class MainActivity extends Activity { @Override public void onCreate(Bundle savedInstanceState) { setTitle(R.string.TitleWhichYouWantToDisplay); // OR You can also use the line below // setTitle("MyTitle") setContentView(R.layout.activity_main); } }

如果你在活动中,最简单的方法是调用this.setTitle("…")。 如果你在一个片段中,只需调用getActivity().setTitle("…");

这样可以让你随时更改标题,不需要在setContentView(r.b ayout.activity_test)之前调用它;

在onCreateView中添加这个:

(activity as AppCompatActivity).supportActionBar?.title ="My APP Title"

您可以在清单文件中为每个活动定义标签。

一个活动的正常定义是这样的:

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

其中标题文本应替换为此活动的字符串资源的id。

如果希望动态地设置标题文本,也可以从代码中设置它。

setTitle(address.getCity());

在oncreate方法中,这一行将标题设置为活动的特定地址所在的城市。

在Activity.onCreate()回调中或在另一个需要更改标题的地方:

getSupportActionBar().setTitle("Whatever title");