如何在Android中设置操作栏的标题

N S*_*rma 0 android android-appcompat android-actionbar android-actionbar-compat

您好我正在使用演示应用程序,我需要ActionBar在其中心设置标题.我已经尝试了一些不适合我的SO帖子.我正在试用Android 4.3手机.

/sf/answers/1523937411/,/sf/answers/1347124341/

但没有什么对我有用.有没有办法ActionBar在Android中使用appcompat 设置中心标题?

我这样做就像下面但仍然标题在左侧.

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" />
Run Code Online (Sandbox Code Playgroud)

在活动中

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);
Run Code Online (Sandbox Code Playgroud)

ᴛʜᴇ*_*ᴛᴇʟ 5

我知道这个问题很老,但我能找到解决方案.

一种不需要您创建自定义操作栏的解决方案.

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);
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

然后,只需在您的上面调用onCreate():

centerTitle();
Run Code Online (Sandbox Code Playgroud)

而已.那么简单.
希望它可以帮助某人.