我搜索了很多但找不到方法,如何将标题设置在 ActionBar 的中心而不是左对齐。我使用下面的代码将标题设置在中心:
ViewGroup decorView= (ViewGroup) this.getWindow().getDecorView();
LinearLayout root= (LinearLayout) decorView.getChildAt(0);
FrameLayout titleContainer= (FrameLayout) root.getChildAt(0);
TextView title= (TextView) titleContainer.getChildAt(0);
title.setGravity(Gravity.CENTER);
但它给出的错误如下:
ClassCastException : com.android.internal.widget.ActionBarView can not
be cast to android.widget.TextView.
任何其他解决方案..任何帮助将不胜感激。
最佳答案
您可以创建自定义布局并将其应用到 actionBar。
为此,请执行以下 2 个简单步骤:
Java 代码
getSupportActionBar().setDisplayOptions(ActionBar.DISPLAY_SHOW_CUSTOM); getSupportActionBar().setCustomView(R.layout.actionbar);
其中 R.layout.actionbar
是以下布局。
XML
<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_gravity="center" android:orientation="vertical"> <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_gravity="center" android:id="@+id/action_bar_title" android:text="YOUR ACTIVITY TITLE" android:textColor="#ffffff" android:textSize="24sp" /> </LinearLayout>
它可以像你想要的那样复杂。试试看!
编辑:
要设置 background
,您可以在容器布局中使用属性 android:background
(在这种情况下为 LinearLayout)。您可能需要将布局高度 android:layout_height
设置为 match_parent
而不是 wrap_content
。
此外,您还可以为其添加LOGO/ICON。为此,只需在布局中添加一个 ImageView,并将布局方向属性 android:orientation
设置为水平(或简单地使用 RelativeLayout 并自行管理)。
要动态更改上述自定义操作栏的标题,请执行以下操作:
TextView title=(TextView)findViewById(getResources().getIdentifier("action_bar_title", "id", getPackageName()));
title.setText("Your Text Here");
关于android - 如何在默认主题中对齐 ActionBar 中心的标题(Theme.Holo.Light),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18418635/