我知道這個線程,如果比較老了,但我想還是分享我解決這個問題,因爲它可能是一些有用的。 它工作得非常好,即使對於不同的drawables,取決於所選狀態。
我首先做了定義兩個數組SlidingTabLayout
類中(這很容易被外包到其他類):
private int[] imageResId = {
R.drawable.multi_random,
R.drawable.single_random,
R.drawable.known_person,
};
private int[] imageResSelected = {
R.drawable.multi_random_selected,
R.drawable.single_random_selected,
R.drawable.known_person_selected
};
private int mOldPosition = 0;
現在我們改變SlidingTabLayout
內populateTabStrip()
方法:
for (int i = 0; i < adapter.getCount(); i++) {
View tabView = null;
ImageView tabImageView = null;
if (mTabViewLayoutId != 0) { // HAS TO BE SET FOR THE MOMENT!
// If there is a custom tab view layout id set, try and inflate it
tabView = LayoutInflater.from(getContext()).inflate(mTabViewLayoutId, mTabStrip,
false);
tabImageView = (ImageView) tabView.findViewById(mTabViewTextViewId);
}
if (tabView == null) {
tabView = createDefaultTabView(getContext());
}
if (tabImageView == null && ImageView.class.isInstance(tabView)) {
tabImageView = (ImageView) tabView;
}
int resourceId;
if (i == mViewPager.getCurrentItem()) {
resourceId = imageResSelected[i];
mOldPosition = i;
} else {
resourceId = imageResId[i];
}
tabImageView.setImageResource(resourceId);
tabView.setOnClickListener(tabClickListener);
mTabStrip.addView(tabView);
}
要根據選擇哪個標籤更新圖像,我們在onPageSelected
方法中添加一些行
// This Method is called once the transition is finished
// Change the drawable of the old one..
ImageView view = (ImageView) mTabStrip.getChildAt(mOldPosition);
view.setImageResource(imageResId[mOldPosition]);
// And now change it of the current one
view = (ImageView) mTabStrip.getChildAt(position);
view.setImageResource(imageResSelected[position]);
mOldPosition = position;
最後,我們需要添加自定義選項卡瀏覽:
mSlidingTabLayout.setCustomTabView(R.layout.custom_tab, 0);
贊一個
<?xml version="1.0" encoding="utf-8"?>
<ImageView xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:padding="16dp"
android:layout_weight="1"
android:src="@drawable/multi_random"
/>
該解決方案是遠遠不夠完善,但適合我的需要。也許我可以幫助這個人。
檢查此http://www.mkyong.com/android/android-tablayout-example/ –
http://stackoverflow.com/questions/28125794/slidingtablayout-with-icons-only/28134763#28134763 – Daniel
我需要它,所以我改變了SlidingTabLayout代碼的一點點,使它易於使用圖標的標籤https://github.com/kimkevin/SlidingIconTabLayout – kimkevin