8

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

4

3 回答 3

13

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

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

在发现TabPageIndicator.java

这是私有方法 ( addTab()) 的一部分,因此在不修改库本身的情况下无法更改。

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

如果您想永久更改位置(尽可能永久更改源代码),请更改setCompoundDrawablesWithIntrinsicBounds()方法iconResId中的位置。例如,将图标放在顶部需要是该方法的第二个参数。iconResId

tabView.setCompoundDrawablesWithIntrinsicBounds(0, iconResId, 0, 0);

如果您需要一些更灵活的东西,我想出了这些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;

添加这个方法:

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);
于 2013-05-28T22:20:54.620 回答
8

只需修改 ViewPageIndicator 库的源代码中的 1 行即可达到此效果。

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

原始文件是

180        tabView.setCompoundDrawablesWithIntrinsicBounds( iconResId, 0, 0, 0 );

如果您希望图标位于文本之上,则应将其修改为以下内容。

180        tabView.setCompoundDrawablesWithIntrinsicBounds( 0, iconResId, 0, 0 );

这是更改的屏幕截图

在此处输入图像描述

您现在可能已经猜到了,您可以通过在方法的不同参数中使用 iconResId 将图标放在文本周围的任何位置setCompoundDrawablesWithIntrinsicBounds

于 2013-05-28T22:19:34.637 回答
0

有一种更简洁的方法可以在不修改库的情况下做到这一点。只需将类TabPageIndicator复制并粘贴到您的项目中,然后修改其他答案中指出的行。然后将该类重命名为您喜欢的任何名称,并像使用TabPageIndicator.

于 2014-01-09T16:34:14.063 回答