我正在尝试将自定义TabLayout作为库的一部分进行构建,该库可被其他应用程序使用。此Tablayout中的每个Tab也需要具有自定义背景属性。
public class MyTab extends TabLayout {
Context mContext;
public MyTab(Context context) {
this(context, null);
}
public MyTab(Context context, AttributeSet attrs) {
this(context, attrs, 0);
}
public MyTab(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
setBackground(context.getResources().getDrawable(R.drawable.tab_background));
setTabMode(MODE_SCROLLABLE);
mContext = context;
setSelectedTabIndicatorColor(context.getResources().getColor(R.color.lightest_grey9));
}
@Override
public void addTab(@NonNull Tab tab) {
super.addTab(tab);
setTabGravity(GRAVITY_FILL);
View tabView = LayoutInflater.from(mContext).inflate(R.layout.tab_item_background,null);
TextView textView = (TextView) tabView.findViewById(R.id.tab_text);
textView.setText(tab.getText());
// textView.setFocusable(true);
tabView.setFocusable(true);
tabView.setFocusableInTouchMode(true);
// textView.setBackground(getContext().getResources().getDrawable(R.drawable.tab_item_view_background));
tabView.setBackground(getContext().getResources().getDrawable(R.drawable.tab_item_view_background));
tab.setCustomView(tabView);
}
}
我的要求是:
此方法存在问题:
我想念什么吗?
tab_item_background.xml
<?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" >
<TextView
android:focusableInTouchMode="true"
android:id="@+id/tab_text"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textColor="@color/lightest_grey9" android:background="@drawable/tab_item_view_background"/>
</LinearLayout>
tab_focused.xml
<?xml version="1.0" encoding="utf-8"?>
<shape android:shape="rectangle" xmlns:android="http://schemas.android.com/apk/res/android">
<padding android:left="5dp" android:right="5dp"/>
<size android:height="38dp" android:width="40dp"/>
<stroke android:width="2dp"
android:color="@color/lightest_blue5"/>
</shape>
tab_item_view_background.xml
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:state_focused="true" android:drawable="@drawable/tab_focused">
</item>
</selector>