安卓SeekBar拇指位置的像素值

10
如何在SeekBar中以像素为单位获取拇指的当前位置?
目前,我正在尝试根据计算获取位置。
屏幕宽度、SeekBar宽度、当前寻求进展等等。但是我无法从中获取确切的位置。
有人有任何想法吗?

编程如下所示。

我想在SeekBar拇指的顶部绘制一个组件。

translation = calculateTranslation(this.deviceScreenWidth, seekBarWidth, seekBar1T.getMax(), Integer.valueOf(ConstantData.seekbar_fifth.toString()), topComponentWidth, 0);
        if (currentapiVersion < android.os.Build.VERSION_CODES.HONEYCOMB){
            TranslateAnimation anim = new TranslateAnimation(translation - 1,
                    translation, 0, 0);
            anim.setFillAfter(true);
            anim.setDuration(0);
            edtTextRodUpDown.startAnimation(anim);  
        }else{
            edtTextRodUpDown.setTranslationX(translation);
        }

并计算翻译的方式

    private float calculateTranslation(int screenWidth, int seekBarWidth, int seekMaxProgress, int currentProgress, int componentWidth, int extraDifference){
    double calculatedPosition = 0f;
    calculatedPosition = (double)((double)(seekBarWidth-((screenWidth-seekBarWidth))) / (double)seekMaxProgress) * (double)currentProgress;
    calculatedPosition = calculatedPosition - (double)(componentWidth/2);
    calculatedPosition = calculatedPosition + extraDifference;
    Double d = new Double(calculatedPosition);
    if(d < 0){
        return 0.0f;
    }else if(d + componentWidth > screenWidth){
        return screenWidth-componentWidth;
    }else{
        return d.floatValue();
    }
}
3个回答

26

我做了这个:

int width = seekBar.getWidth()
            - seekBar.getPaddingLeft()
            - seekBar.getPaddingRight();
int thumbPos = seekBar.getPaddingLeft()
            + width
            * seekBar.getProgress()
            / seekBar.getMax();

如何在垂直SeekBar中实现此功能 - Naveen Kumar M
@NaveenKumarM 只需使用getHeight、getPaddingBottom和getPaddingTop即可。我不明白为什么这样不行... - chw

7
你可以使用 getBounds() 方法来获取这个信息。
下面的示例代码用于将一个 TextView 对齐到 seekbar 拖动块的位置。
TextView sliderIndicator = ...
Rect bounds = seekBar.getThumb().getBounds();
sliderIndicator.setTranslationX(seekBar.getLeft() + bounds.left);

谢谢这个解决方案!我认为这是正确的方法,看起来可靠而且顺畅。 - epekel
这是一个完美的解决方案。无需第三方库,只需要这个就可以解决问题。 - TootsieRockNRoll

2
进度条的拇指有一个拇指偏移量,基本上是向右轻微移动。因此,您还必须确保考虑到这一点:
int thumbPos = seekbar.getMeasuredWidth() * seekbar.getProgress() / seekbar.getMax() - seekbar.getThumbOffset();

据我所理解,getThumbOffset()计算的是拇指的宽度,因此不要从位置中减去它。 - CoolMind

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接