[英]How to add Text in a custom action bar for Android
I am able to create an actionbar with a custom back button as such:我能够创建一个带有自定义后退按钮的操作栏,如下所示:
// Calling the action bar
ActionBar actionBar = getSupportActionBar();
// Customize the back button
actionBar.setHomeAsUpIndicator(R.drawable.ic_baseline_arrow_back_24);
// Showing the back button in action bar
actionBar.setDisplayHomeAsUpEnabled(true);
What I am not certain now is that I wish to add a TextView in the same actionbar (towards the end of the actionbar) but I am not clear on how I can do so?我现在不确定的是,我希望在同一个操作栏中(靠近操作栏的末尾)添加一个 TextView,但我不清楚我该怎么做?
also I would need to add a onClickListened on the TextView as I would like for it to perform an action when user click on it.我还需要在 TextView 上添加一个 onClickListened ,因为我希望它在用户单击时执行操作。
Can anyone please let me know how I can achieve that?任何人都可以让我知道我如何实现这一目标?
actionbar.setTitle will change the title. actionbar.setTitle 会改变标题。 Using a Toolbar will be better if you want to customize it.如果您想自定义它,使用工具栏会更好。 can you give a more detailed example on what you are trying to achieve.你能举一个更详细的例子来说明你想要达到的目标。
If I'm not wrong you are trying to add a TextView in your ActionBar which is not possible.如果我没有猜错,您将尝试在 ActionBar 中添加一个 TextView,这是不可能的。 The alternate approach is to use a Toolbar.另一种方法是使用工具栏。
Inside your Toolbar add a ViewGroup (eg LinearLayout, RelativeLayout, etc) and define your TextView inside that ViewGroup.在您的工具栏中添加一个 ViewGroup(例如 LinearLayout、RelativeLayout 等)并在该 ViewGroup 中定义您的 TextView。
Code Example代码示例
<androidx.appcompat.widget.Toolbar
android:id="@+id/toolbar"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="?attr/colorPrimary"
android:minHeight="?attr/actionBarSize"
android:theme="?attr/actionBarTheme">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:id="@+id/your_textview"
android:layout_width="wrap_content"
android:layout_height="wrap_content"/>
</LinearLayout>
</androidx.appcompat.widget.Toolbar>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.