[英]How to set the title of action bar in center in Android
您好,我正在开发演示应用程序,需要在其中的ActionBar
中设置标题。 我尝试了一些SO的帖子,这些帖子对我不起作用。 我正在Android 4.3手机上尝试。
https://stackoverflow.com/a/21770534/2455259 , https://stackoverflow.com/a/19244633/2455259
但对我没有任何作用。 有什么方法可以使用appcompat将ActionBar
的标题设置为Android的中心吗?
我这样做如下,但标题仍在左侧。
center_action_bar_title.xml
<?xml version="1.0" encoding="utf-8"?>
<TextView
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:textSize="18sp" />
活动中
TextView customView = (TextView)
LayoutInflater.from(getActivity()).inflate(R.layout.center_action_bar_title,
null);
ActionBar.LayoutParams params = new
ActionBar.LayoutParams(ActionBar.LayoutParams.MATCH_PARENT,
ActionBar.LayoutParams.MATCH_PARENT, Gravity.CENTER);
customView.setText(text);
((ActionBarActivity)getActivity()).getSupportActionBar().setCustomView(customView, params);
我知道这个问题很老,但是我找到了解决方案。
一种不需要您创建自定义操作栏的解决方案。
private void centerTitle() {
ArrayList<View> textViews = new ArrayList<>();
getWindow().getDecorView().findViewsWithText(textViews, getTitle(), View.FIND_VIEWS_WITH_TEXT);
if(textViews.size() > 0) {
AppCompatTextView appCompatTextView = null;
if(textViews.size() == 1) {
appCompatTextView = (AppCompatTextView) textViews.get(0);
} else {
for(View v : textViews) {
if(v.getParent() instanceof Toolbar) {
appCompatTextView = (AppCompatTextView) v;
break;
}
}
}
if(appCompatTextView != null) {
ViewGroup.LayoutParams params = appCompatTextView.getLayoutParams();
params.width = ViewGroup.LayoutParams.MATCH_PARENT;
appCompatTextView.setLayoutParams(params);
appCompatTextView.setTextAlignment(View.TEXT_ALIGNMENT_CENTER);
}
}
}
然后,只需在onCreate()
上调用它即可:
centerTitle();
而已。 这么简单。
希望它可以帮助某人。
我认为使用自定义操作栏是自定义操作的最佳方法! 首先,您应该为操作栏构建xml文件,这是一个示例:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/custom_actionbar_relative_layout_main"
android:layout_width="match_parent"
android:layout_height="48dp"
android:background="@color/actionbar_background"
android:enabled="false" >
<TextView
android:id="@+id/textviewactivityname"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:layout_centerInParent="true"
android:layout_centerVertical="true"
android:background="@android:color/transparent"
android:gravity="center_vertical"
android:text="text"
android:textAlignment="center"
android:textColor="@android:color/white"
android:textSize="18sp" />
</RelativeLayout>
然后,您应该使用LayoutInflater对该布局进行参考:
ViewGroup actionBarLayout = (ViewGroup) youractivity.getLayoutInflater().inflate(R.layout.nameofxmlfile, null);
最后,您应该将此设置为操作栏的布局:
ActionBar actionBar = youractivity.getSupportActionBar();
actionBar.setDisplayShowCustomEnabled(true);
actionBar.setCustomView(actionBarLayout);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.