Java 代码实现 自定义tablayout,且可以实现选中字体加粗
时间: 2024-03-02 15:52:04 浏览: 19
好的,这是一个简单的 Java 代码实现自定义 TabLayout 并选中字体加粗的示例:
首先,创建一个自定义的 TabLayout 类 CustomTabLayout 继承自 TabLayout:
```java
public class CustomTabLayout extends TabLayout {
public CustomTabLayout(Context context) {
super(context);
}
public CustomTabLayout(Context context, AttributeSet attrs) {
super(context, attrs);
}
public CustomTabLayout(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
}
@Override
public void addTab(Tab tab, boolean setSelected) {
super.addTab(tab, setSelected);
if (setSelected) {
// 设置选中的Tab的字体加粗
setTabBold(tab);
}
}
@Override
public void setOnTabSelectedListener(@Nullable OnTabSelectedListener listener) {
super.setOnTabSelectedListener(new OnTabSelectedListener() {
@Override
public void onTabSelected(Tab tab) {
// 设置选中的Tab的字体加粗
setTabBold(tab);
if (listener != null) {
listener.onTabSelected(tab);
}
}
@Override
public void onTabUnselected(Tab tab) {
// 取消选中的Tab的字体加粗
setTabNormal(tab);
if (listener != null) {
listener.onTabUnselected(tab);
}
}
@Override
public void onTabReselected(Tab tab) {
if (listener != null) {
listener.onTabReselected(tab);
}
}
});
}
// 设置选中的Tab的字体加粗
private void setTabBold(Tab tab) {
TextView textView = tab.getCustomView().findViewById(android.R.id.text1);
textView.setTypeface(null, Typeface.BOLD);
}
// 取消选中的Tab的字体加粗
private void setTabNormal(Tab tab) {
TextView textView = tab.getCustomView().findViewById(android.R.id.text1);
textView.setTypeface(null, Typeface.NORMAL);
}
}
```
在上面的代码中,我们重写了 addTab 和 setOnTabSelectedListener 方法来实现选中的 Tab 加粗。在 addTab 方法中,我们设置了选中的 Tab 为加粗字体;在 setOnTabSelectedListener 方法中,我们监听选中的 Tab 和取消选中的 Tab,并分别设置为加粗字体和普通字体。
最后,在布局文件中使用 CustomTabLayout 来代替 TabLayout:
```xml
<com.example.CustomTabLayout
android:id="@+id/tab_layout"
android:layout_width="match_parent"
android:layout_height="wrap_content"
app:tabMode="fixed"
app:tabGravity="fill" />
```
这样,就可以实现自定义 TabLayout 并选中字体加粗了。