我正在使用ViewPagerIndicator,我想更改选项卡样式,使图标显示在文本上方,而不是默认的将图标放在左侧,标题放在右侧。
我正在使用ViewPagerIndicator,我想更改选项卡样式,使图标显示在文本上方,而不是默认的将图标放在左侧,标题放在右侧。
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;
}
}
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);
master
分支发起的 pull 请求,但应该改为 dev
分支。 - Bart Kiersdev
分支上合并代码,但可能是在另一个仓库里。 - Bart Kiers您可以通过修改ViewPageIndicator库中TabPageIndicator类内addTab方法中的第180行代码来实现此效果(至少在今天的代码版本28/05/2013中是这样的)。
原始文件如下:
180 tabView.setCompoundDrawablesWithIntrinsicBounds( iconResId, 0, 0, 0 );
如果您想让图标位于文本上方,则应将其修改为以下内容。
180 tabView.setCompoundDrawablesWithIntrinsicBounds( 0, iconResId, 0, 0 );
setCompoundDrawablesWithIntrinsicBounds
。有一种更简洁的方法可以实现这个,而不需要修改库。只需将类TabPageIndicator复制并粘贴到您的项目中,并修改其他答案中指出的行。然后将该类重命名为您喜欢的任何名称,并将其用作TabPageIndicator
。