我的 seekBar 样式是 android Widget.AppCompat.SeekBar.Discrete。 我有自己的刻度标记,但正如您所见,它显示在拇指标记的前面,但我不想看到拇指后面的刻度。
以及我所拥有的:
我的 XML:
<android.support.v7.widget.AppCompatSeekBar
style="@style/seekbarStyle"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:max="4"
android:padding="4dp"
android:progress="0"/>
我的风格:
<style name="seekbarStyle" parent="Widget.AppCompat.SeekBar.Discrete">
<item name="tickMark">@drawable/seekbar_tickmark</item>
<item name="android:thumb">@drawable/circle</item>
</style>
最佳答案
这是 AppCompatSeekBar 的一个错误。 我使用扩展 AppCompatSeekBar 的自定义类解决了这个问题:
public class CustomSeekBar extends AppCompatSeekBar {
private Drawable mTickMark;
public CustomSeekBar(Context context) {
this(context, null);
}
public CustomSeekBar(Context context, AttributeSet attrs) {
this(context, attrs, android.support.v7.appcompat.R.attr.seekBarStyle);
}
public CustomSeekBar(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
applyAttributes(attrs, defStyleAttr);
}
private void applyAttributes(AttributeSet rawAttrs, int defStyleAttr)
{
TypedArray attrs = getContext().obtainStyledAttributes(rawAttrs, R.styleable.CustomSeekBar, defStyleAttr, 0);
try {
mTickMark = attrs.getDrawable(R.styleable.CustomSeekBar_tickMarkFixed);
} finally {
attrs.recycle();
}
}
@Override
protected synchronized void onDraw(Canvas canvas) {
super.onDraw(canvas);
drawTickMarks(canvas);
}
@Override
public int getThumbOffset() {
return super.getThumbOffset();
}
void drawTickMarks(Canvas canvas) {
if (mTickMark != null) {
final int count = getMax();
if (count > 1) {
final int w = mTickMark.getIntrinsicWidth();
final int h = mTickMark.getIntrinsicHeight();
final int halfThumbW = getThumb().getIntrinsicWidth() / 2;
final int halfW = w >= 0 ? w / 2 : 1;
final int halfH = h >= 0 ? h / 2 : 1;
mTickMark.setBounds(-halfW, -halfH, halfW, halfH);
final float spacing = (getWidth() - getPaddingLeft() - getPaddingRight() + getThumbOffset() * 2 - halfThumbW * 2) / (float) count;
final int saveCount = canvas.save();
canvas.translate(getPaddingLeft() - getThumbOffset() + halfThumbW, getHeight() / 2);
for (int i = 0; i <= count; i++) {
if(i!=getProgress())
mTickMark.draw(canvas);
canvas.translate(spacing, 0);
}
canvas.restoreToCount(saveCount);
}
}
}
}
使用 attrs.xml:
<resources>
<declare-styleable name="CustomSeekBar">
<attr name="tickMarkFixed" format="reference"/>
</declare-styleable>
</resources>
并且在布局中,您必须使用 tickMarkFixed 而不是 tickMark。
关于android - 为什么 seekbar 刻度标记显示在拇指前面?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41490306/