¿Cómo agregar TextView en medio de pulgar SeekBar?
Estoy trabajando en Android . Quiero hacer un SeekBar
. En el pulgar de SeekBar
quiero mostrar el progreso (probablemente en un TextView
alineado sobre el pulgar que se mueve junto con el pulgar).
Este es mi XML para SeekBar
y TextView
.
- Debe pasar en una vista no nula
- Acceso a TextView desde otra clase
- Cómo manejar el botón de nuevo de la vista de búsqueda en android
- El cajón de navegación es lento con vista compleja
- ¿Cómo podemos agregar maxlength en SearchView?
<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" />
Y este mi código para hacer alinear para el texto
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());
Pero el texto no se muestra en el centro de ese pulgar. Por favor, sugerirme lo que debo hacer por esto.
- ¿Cómo puedo cerrar un SearchView mediante programación?
- Android SlidingPaneLayout se desvanece en las vistas incorrectas
- Vincular la vista personalizada de Android a una xml de diseño específico (¿es posible?)
- Android DataBinding dónde obtener el contexto?
- Android View con View.GONE sigue recibiendo onTouch y onClick
- Android: uso de la vista personalizada en el widget
- Efectos del acolchado negativo
- Cómo utilizar RenderScript con SurfaceView / View
Si entiendo bien su pregunta, usted quiere colocar el texto dentro del pulgar en un buscador así:
El Android Seekbar no expone ningún método público o protegido que le permita establecer un texto en el pulgar. Por lo tanto, no puede implementar una solución con Android SeekBar tal como está.
Como una solución, usted puede escribir su propio CustomSeekBar.
El Android SeekBar extiende AbsSeekBar . Está en AbsSeekBar que la posición del pulgar está fijada, así:
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); }
Y en el método onDraw () de AbsSeekBar, se dibuja el pulgar:
mThumb.draw(canvas);
Para implementar su propia SeekBar, primero crea una clase CustomSeekBar que extiende AbsSeekBar. A continuación, anula el método setThumPos () de AbsSeekBar en su clase CustomSeekBar y, a continuación, establece la posición de su propio pulgar personalizado.
Su pulgar personalizado sería un View o ViewGroup, por ejemplo, LinearLayout, con un fondo dibujable y un TextView para el porcentaje de progreso del texto.
A continuación, tiene que decidir cómo escribir el porcentaje de progreso al pulgar personalizado. Podrías escribir el porcentaje de texto de progreso en el pulgar en un nuevo método writeTextOnThumb () llamado dentro de setThumbPos (), o podrías exponerlo como un método público en la API de CustomSeekBar.
Antes de entrar en los detalles de una solución, voy a mencionar algo que probablemente ya ha considerado: El usuario, al mover el SeekBar, por lo general tiene su dedo sobre el pulgar, y por lo tanto, probablemente cubrir cualquier texto que podría poner allí , Al menos mientras se mueve el Seekbar. Ahora, tal vez usted está moviendo el SeekBar de forma programática, o tal vez usted está lo suficientemente feliz para el usuario para ver el SeekBar una vez que ha terminado de moverlo y ha retirado su dedo, o tal vez usted puede contar con su usuario para deslizar su dedo por debajo del SeekBar Después de que ella empieza a deslizarlo, para revelar el pulgar. Pero si ese no es el caso, entonces es posible que desee colocar el texto en algún lugar que el dedo del usuario es probable que no sea.
El enfoque descrito a continuación le permitirá posicionar texto en cualquier lugar de la SeekBar que desee, incluso sobre el pulgar. Para permitir esto, anula el método básico de SeekBar onDraw (), en lugar de anular un método que trata específicamente de dibujar el pulgar.
Aquí está una versión aproximada de una clase que dibuja el texto en un SeekBar usando la aproximación antedicha:
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 (ie, 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(); } }
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>