很遗憾,我不觉得这是可能的。原因如下:
像您一样,我尝试使用
ActionBar.Tab.setCustomView()
方法中一个在
RelativeLayout
中居中的
TextView
作为我的选项卡的自定义视图。 我在
RelativeLayout
上使用了
android:layout_width="fill_parent"
和
android:layout_height="fill_parent"
,所以通常情况下
TextView
应该居中显示。然后我尝试只使用没有包含在
RelativeLayout
中的
TextView
:
<TextView xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/tab_title"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:layout_centerHorizontal="true"
android:layout_centerVertical="true"
android:gravity="center"
android:text="TAB_TITLE" />
一般来说,TextView
应该完全填充选项卡,文本应在其中居中。但是仍然不是这种情况:文本仍然没有垂直居中。因此,我决定为TextView
添加android:background="#ffffff"
,以便我可以看到发生了什么。通过背景,我意识到ActionBar.Tab.setCustomView()
方法并没有为选项卡设置自定义布局,而是在我们无法访问的另一个布局中设置自定义视图(据我所知)。使用null
作为父级填充选项卡布局时,android:layout_width="fill_parent"
和android:layout_height="fill_parent"
被忽略,这就解释了为什么我的TextView
中使用它们没有效果。因此,为了使TextView
中的文本垂直居中,我通过编程方式设置了TextView
的高度为非常高的值,使其填充其父级。然后文本就被垂直居中了。请注意,您也可以使用上部填充来创建相同的效果。以下是我的代码:
custom_tab.xml:
<?xml version="1.0" encoding="utf-8"?>
<TextView xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/tab_title"
android:layout_centerHorizontal="true"
android:layout_centerVertical="true"
android:gravity="center"
android:text="TAB_TITLE" />
在我的活动中编写代码以设置自定义视图:
for (int i = 0; i < mSectionsPagerAdapter.getCount(); i++) {
Tab tab = actionBar.newTab();
TextView customTabView = (TextView)getLayoutInflater().inflate(R.layout.custom_tab, null);
customTabView.setText(mSectionsPagerAdapter.getPageTitle(i));
customTabView.setHeight(999);
tab.setCustomView(customTabView);
tab.setTabListener(this);
actionBar.addTab(tab);
}
如果有人知道如何访问设置自定义视图的父视图,请告诉我。希望这可以帮助你。