ViewPagerIndicator选项卡:文本上方的图标

Pab*_*oku 8 icons android viewpagerindicator

我正在使用ViewPagerIndicator ,我想更改选项卡样式,以便我可以获得文本上方的图标,而不是默认设置,将图标放在左侧,标题放在右侧.

A--*_*--C 13

图标总是出现在左侧的原因是因为这段代码:

if (iconResId != 0) {
     tabView.setCompoundDrawablesWithIntrinsicBounds(iconResId, 0, 0, 0);
}
Run Code Online (Sandbox Code Playgroud)

在发现 TabPageIndicator.java

这是私有方法(addTab())的一部分,因此,如果不修改库本身,则无法更改.

幸运的是,这并不难做到.确保已ViewPagerIndicator下载源代码,然后打开TabPageIndicator.java

如果你想永久改变位置(如永久性的,你可以用源代码的变化得到),更改的地点iconResIdsetCompoundDrawablesWithIntrinsicBounds()方法.例如,将图标放在顶部需要iconResId是方法的第二个参数.

tabView.setCompoundDrawablesWithIntrinsicBounds(0, iconResId, 0, 0);
Run Code Online (Sandbox Code Playgroud)

如果你需要一些更灵活的东西,我想出了TabPageIndicator.java应该有效的这些变化(仍然存在).这些更改已反映在我的GitHub上,因此有一个有效的例子.

成员变量:

/**
* Constants to improve readability - no magic numbers.
*/
public final static int LOCATION_LEFT =0;
public final static int LOCATION_UP = 1;
public final static int LOCATION_RIGHT = 2;
public final static int LOCATION_BOTTOM =3;

/**
* Stores the location of the tab icon
*/
private int location = LOCATION_LEFT;

/**
* Used to store the icon.
*/
private int [] drawables = new int [4];

/**
 * Holds the value used by setCompoundDrawablesWithIntrinsicBounds used to denote no icon.
 */
private static int NO_ICON = 0;
Run Code Online (Sandbox Code Playgroud)

添加此方法:

public void setTabIconLocation (int newLocation){
    if (location > LOCATION_BOTTOM || location < LOCATION_LEFT)
        throw new IllegalArgumentException ("Invalid location");
    this.location = newLocation;
    for (int x = 0; x < drawables.length;x++){
        drawables [x] = NO_ICON;
    }
}
Run Code Online (Sandbox Code Playgroud)

addTab(),改变

if (iconResId != 0) {
     tabView.setCompoundDrawablesWithIntrinsicBounds(iconResId, 0, 0, 0);
}
Run Code Online (Sandbox Code Playgroud)

if (iconResId != 0) {
    drawables [location] = iconResId;
    tabView.setCompoundDrawablesWithIntrinsicBounds(drawables[0], drawables[1], drawables[2], drawables[3]);
}
Run Code Online (Sandbox Code Playgroud)

非库实现(取自提供的示例代码)

TabPageIndicator indicator = (TabPageIndicator)findViewById(R.id.indicator);
indicator.setTabIconLocation (TabPageIndicator.LOCATION_UP);
indicator.setViewPager(pager);
Run Code Online (Sandbox Code Playgroud)


Rob*_*ill 8

您可以通过仅修改ViewPageIndicator库的源代码中的1行来实现此效果.

要修改的行是方法内180TabPageIndicator类中的数字addTab(至少在今天的代码版本28/05/2013中)

原始文件是

180        tabView.setCompoundDrawablesWithIntrinsicBounds( iconResId, 0, 0, 0 );
Run Code Online (Sandbox Code Playgroud)

如果您希望图标位于文本顶部,则应将其修改为以下内容.

180        tabView.setCompoundDrawablesWithIntrinsicBounds( 0, iconResId, 0, 0 );
Run Code Online (Sandbox Code Playgroud)

这是更改的屏幕截图

在此输入图像描述

正如您现在可能已经猜到的那样,您可以通过在setCompoundDrawablesWithIntrinsicBounds方法的不同参数中使用iconResId来将图标放在文本的任何位置.