如何在Android中使选项卡栏中的文本居中对齐

9

我希望在选项卡栏中只放置文本,没有图片...我希望水平和垂直居中文本。恰好在正中央。


请给我一个好的答案。 - sam_k
5个回答

32
如果有人仍对不需要创建自己的布局和样式的简单解决方案感兴趣:
  1. 为每个添加的标签使用android.widget.TabHost.TabSpec#setIndicator(CharSequence label)
  2. 使用以下代码居中并包装选项卡内的文本:

int tabCount = tabHost.getTabWidget().getTabCount();
for (int i = 0; i < tabCount; i++) {
    final View view = tabHost.getTabWidget().getChildTabViewAt(i);
    if ( view != null ) {
        // reduce height of the tab
        view.getLayoutParams().height *= 0.66;

        //  get title text view
        final View textView = view.findViewById(android.R.id.title);
        if ( textView instanceof TextView ) {
            // just in case check the type

            // center text
            ((TextView) textView).setGravity(Gravity.CENTER);
            // wrap text
            ((TextView) textView).setSingleLine(false);

            // explicitly set layout parameters
            textView.getLayoutParams().height = ViewGroup.LayoutParams.FILL_PARENT;
            textView.getLayoutParams().width = ViewGroup.LayoutParams.WRAP_CONTENT;
        }
    }
}

真的是完美的解决方案 :) - Ravindra Kushwaha

2
您可以将以下内容添加到XML布局中:android:gravity="center"android:layout_gravity="center"

如果您添加android:layout_gravity="center",则父布局将居中,但如果您使用android:layout_gravity="center",则子视图将居中。 子视图是布局内的元素。 例如,线性布局是您的父级,而在线性布局内,您定义了诸如按钮和文本视图之类的子视图。 - iamtheexp01
@exception 在哪里添加这个 android:layout_gravity="center" 到 TabLayout?它对我没有用,你能回复一下吗?另外我不能给 TabLayout 添加 'android:gravity'。 - Shirish Herwade

1
<android.support.design.widget.TabLayout
app:tabMode="fixed"
app:tabContentStart="0dp" 

0

试试这个,它会对你有帮助的!!!

<?xml version="1.0" encoding="utf-8"?>
 <TabHost xmlns:android="http://schemas.android.com/apk/res/android"
                   android:id="@+id/tabhost"
                    android:layout_width="fill_parent"
                    android:layout_height="wrap_content"
                    android:padding="1dp" >

        <RelativeLayout
            android:layout_width="fill_parent"
            android:layout_height="fill_parent" >

<TabWidget
    android:id="@android:id/tabs"
    android:layout_width="fill_parent"
    android:layout_height="60dp"
    android:layout_alignParentBottom="true" />

<FrameLayout
    android:id="@android:id/tabcontent"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:padding="1dp" >
</FrameLayout>

0
您可以将以下行添加到选项卡布局中,以使文本居中对齐。
                           app:tabGravity="fill"

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接