如何在SeekBar的拇指中间添加TextView?

14

我正在使用Android开发。我想制作一个SeekBar。在SeekBar的拇指上,我想显示进度(可能是在TextView上对齐拇指的文本视图,与拇指一起移动)。

这是我用于SeekBarTextViewXML

<SeekBar
    android:id="@+id/ProgressBar01"
    android:layout_width="fill_parent"
    android:paddingLeft="10px"
    android:paddingRight ="10px"
    android:layout_height="70dp"
    android:layout_below="@+id/incentives_textViewBottemLeft"
    android:max="10"
    android:progressDrawable="@drawable/incentive_progress"
    android:secondaryProgress="0"
    android:thumb="@drawable/incentives_progress_pin"
    android:focusable="false" />

<TextView
    android:id="@+id/incentives_textViewAbove_process_pin"
    android:layout_width="fill_parent"
    android:layout_height="20dp"
    android:layout_below="@+id/incentives_textViewBottemLeft"
    android:layout_marginTop="11dp"
    android:text=""
    android:textStyle="bold"
    android:textColor="#FFe4e1"
    android:textSize="15sp" />

以下是我编写的让文本对齐的代码

int xPos = ((mSkbSample.getRight() - mSkbSample.getLeft()) / mSkbSample.getMax()) * mSkbSample.getProgress();
v1.setPadding(xPos+m,0,0,0);
v1.setText(String.valueOf(progress).toCharArray(), 0, String.valueOf(progress).length());  

但是文本没有显示在那个 thumb 的中心。请建议我应该怎么做。


请查看此链接http://www.anddev.org/decorated_and_animated_seekbar_tutorial-t10937.html,希望您能够得到解决问题的想法。 - Jaiprakash Soni
3个回答

23
如果我理解您的问题正确,您想在进度条的拇指内放置文本,如下所示:

enter image description here

安卓SeekBar没有公开或受保护的方法可以让你在拇指上设置文本。因此,你不能直接使用安卓SeekBar来实现解决方案。
作为解决方案,你可以编写自己的CustomSeekBar。
安卓SeekBar继承了AbsSeekBar。正是在AbsSeekBar中设置了拇指的位置,就像这样:
 private void setThumbPos(int w, Drawable thumb, float scale, int gap) {
    int available = w - mPaddingLeft - mPaddingRight;
    int thumbWidth = thumb.getIntrinsicWidth();
    int thumbHeight = thumb.getIntrinsicHeight();
    available -= thumbWidth;

    // The extra space for the thumb to move on the track
    available += mThumbOffset * 2;

    //Determine horizontal position
    int thumbPos = (int) (scale * available);

    //Determine vertical position
    int topBound, bottomBound;
    if (gap == Integer.MIN_VALUE) {
        Rect oldBounds = thumb.getBounds();
        topBound = oldBounds.top;
        bottomBound = oldBounds.bottom;
    } else {
        topBound = gap;
        bottomBound = gap + thumbHeight;
    }

    //Set the thumbs position
    thumb.setBounds(thumbPos, topBound, thumbPos + thumbWidth, bottomBound);
}

在 AbsSeekBar 的 onDraw() 方法中,绘制了滑块。
mThumb.draw(canvas);

为了实现自己的SeekBar,您首先需要创建一个CustomSeekBar类,该类扩展了AbsSeekBar。然后在您的CustomSeekBar类中覆盖AbsSeekBar的setThumbPos()方法,并在那里设置自己自定义的滑块的位置。
您的自定义滑块将是一个View或ViewGroup,例如LinearLayout,带有背景可绘制对象和用于百分比进度文本的TextView。
然后,您必须决定如何将百分比进度写入自定义滑块。您可以在setThumbPos()内部调用新的writeTextOnThumb()方法在滑块上写入百分比进度文本,或者您可以将其作为公共方法暴露在CustomSeekBar的API中。

我想在SeekBar的拇指上放置文本。我不明白你的意思,请将源代码发送到saiyadamreddy@gmail.com。请帮帮我,提前感谢您的帮助。 - sai
@Gunnar Karlsson,您能否更新您的答案并提供完整的解决方案? - Pankaj Kumar
2
这个答案确实有其优点 - 但是setThumbPos()是一个私有方法。在Java中,您无法覆盖私有方法。 - SheedySheedySheedy
我做不到...看起来更复杂了 :( - Maveňツ

6
在详细介绍解决方案之前,我想提一下你可能已经考虑过的事情:当用户移动SeekBar时,通常会把手指放在滑块上方,因此在移动SeekBar时,她可能会遮挡住任何你可能放在那里的文本。现在,也许你正在以编程方式移动SeekBar,或者你满足于用户在完成移动并移开手指后查看SeekBar,或者你可以指望用户在开始滑动SeekBar后将手指滑到其下方,以显示滑块。但如果不是这种情况,那么你可能希望将文本放置在用户手指可能不会覆盖的地方。
下面描述的方法应该允许你将文本放置在SeekBar上的任何位置,包括在滑块上方。为了实现这一点,它重写了SeekBar的基本onDraw()方法,而不是重写一个专门处理绘制滑块的方法。
以下是使用上述方法在SeekBar上绘制文本的类的一个粗略版本:
public class SeekBarWithText extends SeekBar {

  private static final int textMargin = 6;
  private static final int leftPlusRightTextMargins = textMargin + textMargin;
  private static final int maxFontSize = 18;
  private static final int minFontSize = 10;

  protected String overlayText;
  protected Paint textPaint;

  public SeekBarWithText(Context context) {
    super(context);
    Resources resources = getResources();

    //Set up drawn text attributes here
    textPaint = new Paint(Paint.ANTI_ALIAS_FLAG);
    textPaint.setTypeface(Typeface.DEFAULT_BOLD);
    textPaint.setTextAlign(Align.LEFT);
  }

  //This attempts to ensure that the text fits inside your SeekBar on a resize
  @Override
  protected void onSizeChanged(int w, int h, int oldw, int oldh) {
    super.onSizeChanged(w, h, oldw, oldh);
    setFontSmallEnoughToFit(w - leftPlusRightTextMargins)));
  }

  //Finds the largest text size that will fit
  protected void setFontSmallEnoughToFit(int width) {
    int textSize = maxTextSize;
    textPaint.setTextSize(textSize);
    while((textPaint.measureText(sampleText) > width) && (textSize > minTextSize)) {
      textSize--;
      textPaint.setTextSize(textSize);
    }
  }

  //Clients use this to change the displayed text
  public void setOverlayText(String text) {
    this.overlayText = text;
    invalidate();
  }

  //Draws the text onto the SeekBar
  @Override
  protected synchronized void onDraw(Canvas canvas) {
    //Draw everything else (i.e., the usual SeekBar) first
    super.onDraw(canvas);

    //No text, no problem
    if(overlayText.length() == 0) {
      return;
    }

    canvas.save();

    //Here are a few parameters that could be useful in calculating where to put the text
    int width = this.getWidth() - leftPlusRightTextMargins;
    int height = this.getHeight();

    //A somewhat fat finger takes up about seven digits of space 
    // on each side of the thumb; YFMV
    int fatFingerThumbHangover = (int) textPaint.measureText("1234567");

    float textWidth = textPaint.measureText(overlayText);

    int progress = this.getProgress();
    int maxProgress = this.getMax();
    double percentProgress = (double) progress / (double) maxProgress;
    int textHeight = (int) (Math.abs(textPaint.ascent()) + textPaint.descent() + 1);

    int thumbOffset = this.getThumbOffset();

    //These are measured from the point textMargin in from the left of the SeekBarWithText view.
    int middleOfThumbControl = (int) ((double) width * percentProgress); 
    int spaceToLeftOfFatFinger = middleOfThumbControl - fatFingerThumbHangover;
    int spaceToRightOfFatFinger = (width - middleOfThumbControl) - fatFingerThumbHangover; 

    int spaceToLeftOfThumbControl = middleOfThumbControl - thumbOffset;
    int spaceToRightOfThumbControl = (width - middleOfThumbControl) - thumbOffset; 

    int bottomPadding = this.getPaddingBottom();
    int topPadding = this.getPaddingTop();

    //Here you will use the above and possibly other information to decide where you would 
    // like to draw the text.  One policy might be to draw it on the extreme right when the thumb
    // is left of center, and on the extreme left when the thumb is right of center.  These
    // methods will receive any parameters from the above calculations that you need to
    // implement your own policy.
    x = myMethodToSetXPosition();
    y = myMethodToSetYPosition();

    //Finally, just draw the text on top of the SeekBar
    canvas.drawText(overlayText, x, y, textPaint);

    canvas.restore();
  }
}

谢谢。一个问题:这行代码 int middleOfThumbControl = (int) ((double) width * percentProgress); 是否确切地将文本放置在拇指的中心位置?对于我的垂直滑动条来说,它并不是这样的。因为100%(percentProgress)在滑动条的顶部,但是拇指的中心并没有与其一起移动到顶部(只有拇指的顶部接触到了滑动条的顶部)。你知道我是什么意思吗?我找不到适用于所有屏幕尺寸的好解决方案,任何帮助都将不胜感激。 - Simon Schubert
1
@Simon Schubert:我的代码是为了水平的SeekBar而写的;我还没有尝试过垂直的。然而,你所描述的问题似乎需要你偏移拇指高度的一半。getThumbOffset()可能会返回你需要的值。如果不行,你可以尝试使用getThumb()(它返回一个Drawable),然后检索该Drawable的高度以获取拇指的高度。 - Carl
1
谢谢你,Carl。我按照你说的做了(我相信),但是它让我感到很奇怪。坐标一直有点不对。最终,我覆盖了setProgressAndThumb方法,并在可绘制对象的中间绘制了文本。感谢你的关注。 - Simon Schubert
我在我的应用程序中使用了这种方法的一个变体,似乎效果还不错,也许你只需要微调一下: https://play.google.com/store/apps/details?id=com.goalstate.WordGames.FullBoard.trialsuite - Carl

-4
check this put trees of relative layout to put text on top of seekbar

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:id="@+id/relativeLayout0" >

    <Button
        android:id="@+id/button2"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignBaseline="@+id/button1"
        android:layout_alignBottom="@+id/button1"
        android:layout_alignParentRight="true"
        android:text="Button" />

    <RelativeLayout
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignBottom="@+id/button1"
        android:layout_marginBottom="0dp"
        android:layout_toRightOf="@+id/button1" >

        <SeekBar
            android:id="@+id/seekBar1"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_alignParentLeft="true"
            android:layout_alignParentTop="true" />

        <TextView
            android:id="@+id/textView1"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_alignParentLeft="true"
            android:layout_centerVertical="true"
            android:text="Large Text"
            android:textAppearance="?android:attr/textAppearanceLarge" />

        <TextView
            android:id="@+id/textView2"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_alignBottom="@+id/seekBar1"
            android:layout_alignParentRight="true"
            android:text="Large Text"
            android:textAppearance="?android:attr/textAppearanceLarge" />

        <RelativeLayout
            android:id="@+id/relativeLayout1"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_centerHorizontal="true"
            android:layout_centerVertical="true" >
        </RelativeLayout>

        <TextView
            android:id="@+id/textView3"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_alignTop="@+id/relativeLayout1"
            android:layout_centerHorizontal="true"
            android:text="Large Text"
            android:textAppearance="?android:attr/textAppearanceLarge" />
    </RelativeLayout>
    enter code here
    <Button
        android:id="@+id/button1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"`enter code here`
        android:layout_alignParentLeft="true"
        android:layout_alignParentTop="true"
        android:layout_marginLeft="24dp"
        android:text="Button" />

</RelativeLayout>

1
请解释您所做的事情以及如何解决问题。仅粘贴一些代码可能会让一些读者感到困惑。 - David Medenjak

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