Android:调整SlidingTabLayout.java和SlidingTabStrip.java中选择器的宽度

Android: Adjusting the Width of the Selector in SlidingTabLayout.java and SlidingTabStrip.java

我正在尝试根据选项卡中文本的大小调整位于选项卡下方的选择器线(或条带)的宽度。所以,我希望条带的长度也应该与文本的长度相同。我怎样才能做到这一点?提前致谢。

我终于成功了,我没有在 createDefaultTabView() 方法中为 TextView 设置填充,而是使用边距设置了自定义 LayoutParams。修改后的代码如下:

protected TextView createDefaultTabView(Context context) {
    int padding = (int) (14 * getResources().getDisplayMetrics().density);
    TextView textView = new TextView(context);
    textView.setGravity(Gravity.CENTER);
    textView.setTextSize(TypedValue.COMPLEX_UNIT_SP, TAB_VIEW_TEXT_SIZE_SP);
    textView.setTypeface(Typeface.DEFAULT);

    LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT));
    params.setMargins(padding, padding, padding, 0);

    textView.setLayoutParams(params);
    TypedValue outValue = new TypedValue();
    getContext().getTheme().resolveAttribute(android.R.attr.selectableItemBackground,
            outValue, true);
    textView.setBackgroundResource(outValue.resourceId);
    textView.setPadding(0, 0, 0, padding);
    return textView;
}

此处的数字 14 可以根据您的间距要求进行更改,但根据问题,选择器会根据选项卡文本的宽度调整其宽度。