直接看效果。tab前面加个icon
话不多说。
想要实现,就不能用默认的tab了。直接设置。我没实现成功。
view_special_tab.xml 文件 就是一个图标加一个textview ,我这里文字选中和不选中都要求使用黑色。就没有使用选择器。小图标使用了选择器。自动切换状态。也就是显示和隐藏。
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="horizontal"
android:paddingLeft="8dp"
android:paddingRight="8dp">
<RadioButton
android:id="@+id/rb_tab"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:background="@color/transparent"
android:button="@drawable/selector_special_tab_check"
android:clickable="false" />
<TextView
android:id="@+id/tv_tab"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textColor="#000000"
android:textSize="14sp" />
</LinearLayout>
小图标的Selector selector_special_tab_check.xml
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:drawable="@drawable/img_tab_location" android:state_selected="true" />
<item android:drawable="@drawable/shape_rectangle_special_tab_icon" android:state_selected="false" />
</selector>
非选中状态下,其实就是一个透明的shape shape_rectangle_special_tab_icon.xml
<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
android:shape="rectangle">
<solid android:color="@color/transparent" />
<corners android:radius="20dp" />
<size android:height="12dp"
android:width="12dp"/>
</shape>
封装成一个view ,我这里叫SpecialTabView
import android.content.Context;
import android.support.annotation.Nullable;
import android.util.AttributeSet;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.TextView;
import com.maiya.core.common.utils.Utils;
import com.maiya.suixingou.R;
/**
* Created by chenxiangxiang on 2019/3/5.
*/
public class SpecialTabView extends LinearLayout {
private TextView tvTab;
public SpecialTabView(Context context) {
this(context, null);
}
public SpecialTabView(Context context, @Nullable AttributeSet attrs) {
this(context, attrs, 0);
}
public SpecialTabView(Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
init(context);
}
private void init(Context context) {
View view = LayoutInflater.from(context).inflate(R.layout.view_special_tab, this);
tvTab = view.findViewById(R.id.tv_tab);
}
public SpecialTabView setText(String text) {
if (!Utils.isEmpty(text)) {
tvTab.setText(text);
}
return this;
}
}
然后就是使用了。
SpecialTabView tabView = null;
for (int i = 0; i < headers.size(); i++) {
tabView = new SpecialTabView(getContext());
tabLayout.addTab(tabLayout.newTab().setCustomView(tabView.setText(headers.get(i))));
}
这样,就可以了。既可以点击切换。也可以和recyclerview实现联通切换tab。且可以自动设置状态
这是随心购的一个需求。欢迎大家使用随心购,随心购是一款既可以省钱又可以挣钱的app。 自己用的话,可以寻找淘宝和天猫的隐藏优惠券。节省不少money。 也可以分享优惠券,分享淘宝和天猫商品挣佣金。