我按照此tutorial创建了SlidingTabLayout。它工作正常,但我想自定义它来添加图标而不是文本。我在一个问题中使用了以下代码:
Adapter.java
private int[] imageResId = {
R.drawable.ic_tab_all,
R.drawable.ic_tab_fav,
R.drawable.ic_tab_profile
};
@Override
public CharSequence getPageTitle(int position) {
Drawable image = context.getResources().getDrawable(imageResId[position]);
image.setBounds(0, 0, image.getIntrinsicWidth(), image.getIntrinsicHeight());
SpannableString sb = new SpannableString(" ");
ImageSpan imageSpan = new ImageSpan(image, ImageSpan.ALIGN_BOTTOM);
sb.setSpan(imageSpan, 0, 1, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
return sb;
}
custom_tab.xml
<?xml version="1.0" encoding="utf-8"?>
<TextView xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textSize="12sp"
android:textStyle="bold"
android:background="?android:selectableItemBackground"
android:padding="16dp" />
MainActivity.java
mTabs.setCustomTabView(R.layout.custom_tab, 0);
mTabs.setViewPager(mPager);
但我仍然需要了解以下内容:
答案 0 :(得分:0)
在创建时尝试此操作:tabLayout = (TabLayout) findViewById(R.id.tabs);
tabLayout.setupWithViewPager(viewPager);
setIconForTabs(tabLayout);
这两种方法:
public int getIconsForTabs(int i) {
int[] imageResId = {
R.drawable.ic_action_action_event,
R.drawable.ic_action_av_my_library_books,
R.drawable.ic_action_maps_location_history,
R.drawable.ic_action_content_report
};
return imageResId[i];
}
}
private void setIconForTabs(TabLayout tabLayout) {
Drawable drawable;
for (int i = 0; i < 4; i++) {
drawable = ContextCompat.getDrawable(this, getIconsForTabs(i));
if (drawable != null) {
drawable.mutate();
drawable.setColorFilter(Color.yourColor, PorterDuff.Mode.SRC_ATOP);
}
tabLayout.getTabAt(i).setIcon(drawable);
tabLayout.getTabAt(i).setText("");
}
}
和xml <android.support.design.widget.TabLayout
android:id="@+id/tabs"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
您需要使用支持设计库
我希望这会对你有所帮助。