android v7里的Tablayout里,tabItem可以直接设置一个icon,但是不论你的图片大小是多少,它都会给你弄成一个小图标,这有时候就没法实现UI上的效果。
直接在TabItem设置icon的效果:,xml:
<android.support.design.widget.TabLayout
app:tabIndicatorHeight="0dp"
android:layout_width="match_parent"
android:layout_height="wrap_content">
<android.support.design.widget.TabItem
android:icon="@drawable/ic_relative_true"
android:text="hello"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
<android.support.design.widget.TabItem
android:icon="@drawable/ic_relative_true"
android:text="hello"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
<android.support.design.widget.TabItem
android:icon="@drawable/ic_relative_true"
android:text="hello"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
</android.support.design.widget.TabLayout>
效果图是:
实现1. XML: item_tab(这里可以直接设置图片和文字的选中状态):
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:gravity="center"
android:layout_width="wrap_content"
android:layout_height="wrap_content">
<ImageView
android:id="@+id/iv"
android:src="@drawable/ic_relative_true"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
<TextView
android:layout_marginTop="3dp"
android:textColor="@color/font2"
android:id="@+id/tv"
android:textSize="13sp"
android:text="title"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
</LinearLayout>
2.JAVA:
private void init() {
title.setText("行业中心");
if (list == null) {
list = new ArrayList<>(3);
list.add(new HardNewFragment());
list.add(new ShortMsgFragment());
list.add(new RelativeFragment());
}
if (adapter == null) {
adapter = new FVAdapter(getChildFragmentManager(), list);
}
industryPager.setAdapter(adapter);
industryTab.setupWithViewPager(industryPager);
industryPager.setCurrentItem(0);
//设置TabItem的View(一定要在设置完适配器之后进行设置)
industryTab.getTabAt(0).setCustomView(getview("要闻", R.drawable.hardnews_state));
industryTab.getTabAt(1).setCustomView(getview("短讯", R.drawable.ic_short_msg));
industryTab.getTabAt(2).setCustomView(getview("相关", R.drawable.ic_relative_state));
}
//创建Tablayout的CustomView
private View getview(String title, int icon) {
View view = LayoutInflater.from(getActivity()).inflate(R.layout.item_view, null);
TextView tv = view.findViewById(R.id.tv);
ImageView iv = view.findViewById(R.id.iv);
tv.setText(title);
iv.setImageResource(icon);
return view;
}