6

android.support.v4.view.PagerTabStrip在 xml 中定义如下:

<android.support.v4.view.ViewPager xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/pager"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity">

    <!--
    This title strip will display the currently visible page title, as well as the page
    titles for adjacent pages.
    -->
    <android.support.v4.view.PagerTabStrip android:id="@+id/pager_title_strip"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_gravity="top"
        android:background="#33b5e5"
        android:textColor="#fff"
        android:paddingTop="4dp"
        android:paddingBottom="4dp" />

</android.support.v4.view.ViewPager>

我怎样才能改变TabIndicater颜色?它可以通过setTabIndicatorColor(int color)以编程方式更改,但我需要找到一种在 xml 中执行此操作的方法。

4

1 回答 1

9

主要方法是使一个类扩展PagerTabStrip,例如,名为MyPagerTabStrip

package com.example.View; /// change this package to yourselves.

public class MyPagerTabStrip extends PagerTabStrip
{
    public MyPagerTabStrip(Context context, AttributeSet attrs)
    {
    super(context, attrs);
    final TypedArray a = context.obtainStyledAttributes(attrs,
                                  R.styleable.MyPagerTabStrip);
    setTabIndicatorColor(a.getColor(
            R.styleable.MyPagerTabStrip_indicatorColor, Color.BLUE));
    a.recycle();
    }

}

在 res/values 文件夹中新建一个名为attrs.xml的文件,该文件的内容是:

<?xml version="1.0" encoding="utf-8"?>

<declare-styleable name="MyPagerTabStrip">
    <attr name="indicatorColor" format="reference|color" />
</declare-styleable>

同一个文件夹,如果不存在则新建一个名为styles.xml的文件,将以下代码放入文件中:

<style name="Pager">
    <item name="android:textColor">#ffffff</item>
    <item name="indicatorColor">#6f8dc5</item>
</style>

最后,您的布局 xml 文件是:

<android.support.v4.view.ViewPager xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/pager"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">

<!--
This title strip will display the currently visible page title, as well as the page
titles for adjacent pages.
-->
<com.example.view.MyPagerTabStrip android:id="@+id/pager_title_strip"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_gravity="top"
    android:background="#33b5e5"
    android:textColor="#fff"
    android:paddingTop="4dp"
    android:paddingBottom="4dp" />

于 2012-12-25T07:49:11.787 回答