我正在使用ViewPagerIndicator
并且我想更改标签样式,以便可以在文本上方获取图标,而不是默认图标,该图标将图标放在左侧,标题放在右侧。

最佳答案

图标始终显示在左侧的原因是由于以下这段代码:

if (iconResId != 0) {
     tabView.setCompoundDrawablesWithIntrinsicBounds(iconResId, 0, 0, 0);
}

TabPageIndicator.java 中找到

这是私有(private)方法(addTab())的一部分,因此,如果不修改库本身,就不能更改它。

幸运的是,这并非难事。确保已下载ViewPagerIndicator源代码,然后打开TabPageIndicator.java
如果要永久更改位置(与源代码更改一样永久更改),请在setCompoundDrawablesWithIntrinsicBounds()方法中更改iconResId的位置。例如,将图标放在顶部需要iconResId作为方法的第二个参数。
tabView.setCompoundDrawablesWithIntrinsicBounds(0, iconResId, 0, 0);

如果您需要一些更灵活的东西,我想出了这些应该起作用的更改(仍在TabPageIndicator.java中)。这些更改已镜像到on my 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;

添加此方法:
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;
    }
}

addTab()中,更改
if (iconResId != 0) {
     tabView.setCompoundDrawablesWithIntrinsicBounds(iconResId, 0, 0, 0);
}


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

非库实现(摘自提供的示例代码)
TabPageIndicator indicator = (TabPageIndicator)findViewById(R.id.indicator);
indicator.setTabIconLocation (TabPageIndicator.LOCATION_UP);
indicator.setViewPager(pager);

关于android - ViewPagerIndicator选项卡: Icons above Text,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/14735278/

10-12 02:29