我尝试了自己的自定义操作栏,以使操作栏标题居中。有效。但是,在我在操作栏中添加选项菜单后,标题再次向左移动。我应该怎么做才能使标题居中于操作栏的中间? 我的代码是:
ActionBar actionBar = getActionBar();
actionBar.setDisplayHomeAsUpEnabled(false);
actionBar.setDisplayShowCustomEnabled(true);
actionBar.setDisplayShowTitleEnabled(false);
actionBar.setDisplayUseLogoEnabled(false);
actionBar.setDisplayShowHomeEnabled(false);
actionBar.setDisplayOptions(ActionBar.DISPLAY_SHOW_CUSTOM);
View cView = getLayoutInflater().inflate(R.layout.custom_actionbar, null);
actionBar.setCustomView(cView);
我的布局是
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:background="@android:color/holo_blue_light"
android:orientation="vertical" >
<TextView
android:id="@+id/apptitle"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerInParent="true"
android:layout_gravity="center_horizontal|center_vertical"
android:gravity="center_horizontal|center_vertical"
android:text="@string/app_name" />
最佳答案
我确定,您正在使用以下设置自定义主题。
getSupportActionBar().setDisplayOptions(ActionBar.DISPLAY_SHOW_CUSTOM);
getSupportActionBar().setCustomView(R.layout.abs_layout);
如果没有,请添加第一行。自定义布局中的文本居中。 (重力 = 中心)
我还发现了一个类似的链接 here和 here .希望这会有所帮助。
也试试这个。
我能够通过不显示标题来完成我想要的 Activity ,而不是按照您的建议使用 customView。 key 我错过了一段时间是你必须使用 setCustomView(View, ActionVar.LayoutParams) 方法以获得自定义 View 居中,只需在自定义 View 中设置 layout_gravity="center" 布局文件不起作用。这是一个简短的代码 fragment ,展示了我如何 开始工作:
TextView customView = (TextView)
LayoutInflater.from(this).inflate(R.layout.actionbar_custom_title_view_centered,
null);
ActionBar.LayoutParams params = new
ActionBar.LayoutParams(ActionBar.LayoutParams.MATCH_PARENT,
ActionBar.LayoutParams.MATCH_PARENT, Gravity.CENTER);
customView.setText("Some centered text");
getSupportActionBar().setCustomView(customView, params);
此方法至少适用于 3.2、2.3 和 2.2 设备。
来源https://groups.google.com/forum/#!msg/actionbarsherlock/A9Ponma6KKI/Llsp41jWLEgJ
关于android - 如何使android操作栏标题居中对齐?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21770428/