2012-02-14 2 views
11

에서 근무하고 있습니다.입니다. SeekBar을 만들고 싶습니다. 엄지 손가락에서 SeekBar 나는 (아마도 엄지 손가락과 함께 움직이는 엄지 위로 정렬 TextView에) 진행 상황을 보여주고 싶습니다.SeekBar thumb의 중간에 TextView를 추가하는 방법은 무엇입니까?

이것은 내 SeekBarTextView에 대한입니다.

<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()); 

에 대한 정렬을 만들 그러나 텍스트는 엄지 손가락의 센터에 표시되지 않습니다. 제발 내가 이것을 위해해야한다고 제안 해주세요. 나는 당신의 질문 권리를 이해한다면

+0

확인이 링크 http://www.anddev.org/decorated_and_animated_seekbar_tutorial-t10937.html : 여기

은 위의 방법을 사용하여 검색 막대에 텍스트를 그리는 클래스의 거친 버전입니다 문제를 해결하기위한 아이디어를 얻길 바랍니다. –

답변

23

, 당신은 지금처럼 검색 막대에 엄지 손가락의 내부 텍스트를 배치 할 :

enter image description here

안드로이드 SeekBar를 당신을 가능하게하는 모든 공용 또는 보호 방법을 노출하지 않습니다 엄지 손가락에 텍스트를 설정합니다. 따라서 Android SeekBar를 그대로 사용하여 솔루션을 구현할 수는 없습니다.

해결 방법으로, 자신 만의 CustomSeekBar를 작성할 수 있습니다.

안드로이드 SeekBarAbsSeekBar입니다.() 메소드가, 엄지 손가락이 그려

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에서 : : 그것은 엄지 손가락의 위치 설정과 같이되어 AbsSeekBar에서의

mThumb.draw(canvas); 

자신의 SeekBar를 구현하려면 먼저를 만들 AbsSeekBar를 확장하는 CustomSeekBar 클래스입니다. 그런 다음 CustomSeekBar 클래스에서 AbsSeekBar의 setThumPos() 메서드를 재정 의하여 사용자 정의 엄지 위치를 설정합니다.

사용자 정의 엄지 손가락은보기 또는보기 그룹입니다 (예 : LinearLayout, 배경 drawable 및 백분율 진행률 텍스트 용 TextView.

그러면 사용자 정의 엄지 손가락의 비율 진행 방법을 결정해야합니다. setThumbPos() 내부에서 호출 된 새 writeTextOnThumb 메서드()에서 엄지 손가락의 백분율 진행률 텍스트를 작성하거나 CustomSeekBar API에서 공개 메서드로 표시 할 수 있습니다.

+0

나는 무엇을 seekbar 엄지에 텍스트를 놓을 수 있습니다. 귀하의 요점을 얻을 수 없습니다 [email protected]에 소스 코드를 보내 주시기 바랍니다 제발 adavance 덕분에 도와주세요. – sai

+0

@Gunnar Karlsson은 완벽한 솔루션 plz로 답변을 업데이트 할 수 있습니까? –

+2

이 답변에는 장점이 있지만 setThumbPos()는 개인적인 방법입니다. Java의 private 메소드는 대체 할 수 없습니다. – SheedySheedySheedy

6

솔루션의 세부 사항을 살펴보기 전에 먼저 사용자가 이미 생각한 내용을 언급 할 것입니다. 사용자는 SeekBar를 움직일 때 대개 엄지 손가락에 손가락을 위치 시켰기 때문에 텍스트를 덮을 가능성이 큽니다. 적어도 Seekbar가 움직이는 동안 거기에 놓을 수 있습니다. 이제는 프로그래밍 방식으로 SeekBar를 움직이거나 아마도 사용자가 이동을 끝내고 손가락을 떼어 내면 SeekBar를 볼 수있을만큼 행복하거나 아마도 손가락을 움직일 수있는 사용자의 수를 계산할 수 있습니다 아래 SeekBar가 엄지 손가락을 드러내 기 시작합니다. 그러나 그렇지 않은 경우 사용자의 손가락이 이 아닌이 될 가능성이있는 위치에 텍스트를 배치 할 수 있습니다.

아래 설명 된 접근 방식을 사용하면 엄지 손가락을 포함하여 좋아하는 SeekBar의 아무 곳에 나 텍스트를 배치 할 수 있습니다. 이것을 가능하게하기 위해 엄지 그리기를 특별히 다루는 메소드를 오버라이드하지 않고 SeekBar의 기본 onDraw() 메소드를 오버라이드합니다.

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(); 
    } 
} 
+0

고맙다. 한 가지 질문 : 엄지 손가락 중간에 정확하게 배치 된 텍스트는 다음과 같다 :'int middleOfThumbControl = (int) ((double) 너비 100 % (percentProgress) seekbar의 상단에 있기 때문에하지만 엄지 손가락 중간에 가기 (엄지의 상단에만 만지고있다) 모든 화면 크기에 대해 좋은 해결책을 찾을 수 없다면 도움이 될 것입니다. –

+1

@Simon Schubert : 내 코드는 수평 SeekBar 용이므로 시도하지 않았습니다. 그러나, 당신이 설명하는 문제는 엄지 손가락 높이의 절반으로 오프셋을 요구하는 것 같습니다 getThumbOffset()은 필요한 값을 반환 할 수 있습니다. 그렇지 않으면 getThumb()을 시도 할 수 있습니다 (Drawable) 그런 다음 그 드로어 블의 높이를 가져와 엄지 손가락의 높이를 얻으십시오 – Carl

+0

감사합니다. 칼. 나는 네가 한 말을 정확히 (나는 믿는다)했으나 나를 괴롭혔다. 좌표는 항상 틀린 조금이었다. 결국 setProgressAndThumb 메서드를 덮어 쓰고 드로어 블 중간에 텍스트를 그립니다. 관심을 가져 주셔서 감사합니다. –

-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> 
+0

당신이하는 일과 이것이 어떻게 문제를 해결 하는지를 설명하십시오. 일부 코드를 붙여 넣는 것만으로 일부 독자에게는 혼란을 줄 수 있습니다. –

관련 문제