开发者

Creating a SeekBar position popup in Android

I have a SeekBar in my application, and I want it to behave so that when the user is dragging the 'thumb', a Popup ap开发者_开发技巧pears above the thumb (and follows it as the thumb is dragged), and the Popup displays the corresponding positon of the SeekBar (or any other text that position may represent).

Any suggestions?


Check out this blog

@Override
public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
   // TODO Auto-generated method stub
        RelativeLayout.LayoutParams p = new RelativeLayout.LayoutParams(
        RelativeLayout.LayoutParams.WRAP_CONTENT,
        RelativeLayout.LayoutParams.WRAP_CONTENT);
        p.addRule(RelativeLayout.ABOVE, seekBar.getId());
        Rect thumbRect = bar.getSeekBarThumb().getBounds();
        p.setMargins(
        thumbRect.centerX(),0, 0, 0);
        textView.setLayoutParams(p);
        textView.setText(String.valueOf(progress));
    }
  });
 }
}


The thumb is a drawable, so a solution could be to set the thumb to a drawable that includes both thumb and popup with text. That means you would need a drawable/icon for each possible value on your slider, and update it every time the value changes. Looking around I found this, which suggests that others have gone that way when they needed text in their drawables: Convert String to Drawable


The solution I found for this popup following the seek bar is to put the textview in a relative layout right above the seekbar. Then, in seekbar's onProgressChange, set the textView's left margin accordingly using

RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams(widht, height)
params.setLeftMargin(margin)

works great, with some tweaking!

cheers


This must be late however i did it like this .

by getting the bounds of thumb. and setting the x of textview in on progressChanged of seekbar

  @Override
 public void onProgressChanged(SeekBar seekBar, int progress,
    boolean fromUser) {

    mDistance.setText("" + AppConstants.getDistance() + " miles");
   //Get the thumb bound and get its left value
    int x = mSeekBar.getThumb().getBounds().left;
         //set the left value to textview x value
    mDistance.setX(x);
  }


Here's the Kotlin version of the chosen answer and a bit more detail

override fun onProgressChanged(seekBar: SeekBar?, progress: Int, fromUser: Boolean) {
    txtSeekMonthsPopup.text = progress.toString()
    val params: RelativeLayout.LayoutParams = 
    txtSeekMonthsPopup.layoutParams as RelativeLayout.LayoutParams
    val existingMargin = params.marginStart
    params.marginStart = (seekBar?.thumb?.bounds?.left?: existingMargin) + 20 // 20 makes the text view more centered on the thumb
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜