[英]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.