要在Android ViewPager和TabLayout中实现具有线性(矩形)指示器的边距之间,您可以使用自定义的TabLayout.TabIndicatorColorStateList。以下是一个示例代码:
CustomTabLayout
的类,继承自TabLayout。public class CustomTabLayout extends TabLayout {
private int indicatorStartMargin;
private int indicatorEndMargin;
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);
}
public void setIndicatorMargins(int startMargin, int endMargin) {
this.indicatorStartMargin = startMargin;
this.indicatorEndMargin = endMargin;
invalidate();
}
@Override
public void draw(Canvas canvas) {
super.draw(canvas);
View currentTabView = getTabAt(getSelectedTabPosition()).view;
int tabWidth = currentTabView.getWidth();
int indicatorStart = currentTabView.getLeft() + indicatorStartMargin;
int indicatorEnd = currentTabView.getRight() - indicatorEndMargin;
int indicatorTop = getHeight() - getSelectedTabIndicator().getIntrinsicHeight();
int indicatorBottom = getHeight();
getSelectedTabIndicator().setBounds(indicatorStart, indicatorTop, indicatorEnd, indicatorBottom);
getSelectedTabIndicator().draw(canvas);
}
}
TabLayout
替换为CustomTabLayout
。
setIndicatorMargins()
来设置指示器的边距。CustomTabLayout tabLayout = findViewById(R.id.tabLayout);
tabLayout.setIndicatorMargins(16, 16);
这样,您就可以在边距之间实现具有线性(矩形)指示器的Android ViewPager和TabLayout。您可以根据需要调整指示器的起始和结束边距。