不通过重写onDraw方法,通过弹出popwindow的方式实现上述需求
时间: 2024-03-05 08:51:51 浏览: 19
好的,可以通过弹出一个带有指示器的PopupWindow来实现。
在VerticalSeekBar类中添加以下代码:
```java
private PopupWindow popupWindow;
private TextView textView;
public void showIndicator(int progress) {
if (popupWindow == null) {
textView = new TextView(getContext());
textView.setTextColor(Color.WHITE);
textView.setTextSize(14);
textView.setGravity(Gravity.CENTER);
textView.setBackgroundResource(R.drawable.seekbar_indicator_bg);
popupWindow = new PopupWindow(textView, LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
popupWindow.setOutsideTouchable(true);
popupWindow.setFocusable(false);
}
int[] location = new int[2];
getLocationOnScreen(location);
int thumbTop = (int) ((getHeight() - getThumb().getIntrinsicHeight()) * 0.5f);
int thumbLeft = (int) ((getWidth() - getThumb().getIntrinsicWidth()) * 0.5f);
int thumbWidth = getThumb().getIntrinsicWidth();
int thumbHeight = getThumb().getIntrinsicHeight();
int indicatorWidth = dp2px(getContext(), 40);
int indicatorHeight = dp2px(getContext(), 20);
int indicatorX = location[0] - indicatorWidth - thumbWidth;
int indicatorY = location[1] + (getHeight() - indicatorHeight) * progress / getMax() - thumbTop;
textView.setText(String.valueOf(progress));
popupWindow.showAtLocation(this, Gravity.NO_GRAVITY, indicatorX, indicatorY);
}
public void hideIndicator() {
if (popupWindow != null) {
popupWindow.dismiss();
}
}
private int dp2px(Context context, int dp) {
float density = context.getResources().getDisplayMetrics().density;
return (int) (dp * density + 0.5f);
}
```
在Activity中,可以这样使用:
```java
VerticalSeekBar verticalSeekBar = findViewById(R.id.vertical_seekbar);
verticalSeekBar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
@Override
public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
verticalSeekBar.showIndicator(progress);
}
@Override
public void onStartTrackingTouch(SeekBar seekBar) {
}
@Override
public void onStopTrackingTouch(SeekBar seekBar) {
verticalSeekBar.hideIndicator();
}
});
```
在onProgressChanged()方法中弹出PopupWindow,并在PopupWindow中显示进度值。在onStopTrackingTouch()方法中隐藏PopupWindow。
这样就可以通过弹出PopupWindow在滑块旁边显示进度值了。PopupWindow的位置使用了SeekBar的getLocationOnScreen()方法和一些计算。PopupWindow的大小为40dp * 20dp,背景使用了一个Drawable资源。