Detecting thumb position in SeekBar prior to API version 16 - android

Basically, I need to detect when the progress changes in the SeekBar and draw a text view on top of the thumb indicating the progress value.
I do this by implementing a OnSeekBarChangeListener
and on the public void onProgressChanged(SeekBar seekBar, int progress, boolean b) method, I call Rect thumbRect = seekBar.getThumb().getBounds(); to determine where the thumb is positioned.
This works perfectly fine, but apparently getThumb() is only available in API level 16+ (Android 4.1), causing a NoSuchMethodError on earlier versions.
Any idea how to work around this issue?

I was able to use my own class to get the Thumb:
MySeekBar.java
package mobi.sherif.seekbarthumbposition;
import android.content.Context;
import android.graphics.drawable.Drawable;
import android.util.AttributeSet;
import android.widget.SeekBar;
public class MySeekBar extends SeekBar {
public MySeekBar(Context context) {
super(context);
}
public MySeekBar(Context context, AttributeSet attrs) {
super(context, attrs);
}
public MySeekBar(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
}
Drawable mThumb;
#Override
public void setThumb(Drawable thumb) {
super.setThumb(thumb);
mThumb = thumb;
}
public Drawable getSeekBarThumb() {
return mThumb;
}
}
In the activity this works perfectly:
package mobi.sherif.seekbarthumbposition;
import android.app.Activity;
import android.graphics.Rect;
import android.os.Bundle;
import android.util.Log;
import android.widget.SeekBar;
import android.widget.SeekBar.OnSeekBarChangeListener;
public class MainActivity extends Activity implements OnSeekBarChangeListener {
MySeekBar mSeekBar;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mSeekBar = (MySeekBar) findViewById(R.id.seekbar);
mSeekBar.setOnSeekBarChangeListener(this);
}
#Override
public void onProgressChanged(SeekBar seekBar, int progress, boolean b) {
Rect thumbRect = mSeekBar.getSeekBarThumb().getBounds();
Log.v("sherif", "(" + thumbRect.left + ", " + thumbRect.top + ", " + thumbRect.right + ", " + thumbRect.bottom + ")");
}
#Override
public void onStartTrackingTouch(SeekBar seekBar) {
// TODO Auto-generated method stub
}
#Override
public void onStopTrackingTouch(SeekBar seekBar) {
// TODO Auto-generated method stub
}
}

Hopefully this can save some hours for someone else!
I created this method instead of a custom seekBar:
public int getSeekBarThumbPosX(SeekBar seekBar) {
int posX;
if (Build.VERSION.SDK_INT >= 16) {
posX = seekBar.getThumb().getBounds().centerX();
} else {
int left = seekBar.getLeft() + seekBar.getPaddingLeft();
int right = seekBar.getRight() - seekBar.getPaddingRight();
float width = (float) (seekBar.getProgress() * (right - left)) / seekBar.getMax();
posX = Math.round(width) + seekBar.getThumbOffset();
}
return posX;
}

A splendid solution! Thanks.
It's only nessesary to add that to use custom seekbar you need modify your xml
<com.example.MySeekBar
android:id="#+id/..."
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_gravity="center_vertical"
android:layout_weight="1"
android:minHeight="3dp"
android:maxHeight="3dp"
android:progressDrawable="#drawable/seek_bar_2"
android:thumb="#drawable/thumbler_seekbart_circle"
android:thumbOffset="8dp" />
android:thumbOffset="8dp" - is a HALF of a thumb it's better to spesify, thus there will be no mismatching of the text center and the thumb
Positioning can look like this:
int possition = (int) (seekBar.getX() //the beginning of the seekbar
+ seekBar.getThumbOffset() / 2 //the half of our thumb - the text to be above it's centre
+ ((MySeekBar) seekBar).getSeekBarThumb().getBounds().exactCenterX()); //position of a thumb inside the seek bar

#Sherif elKhatib's answer is great but has the disadvantage of caching a copy of the thumb even on API>=16.
I've improved it so that it only caches the Thumb Drawable on API<=15 plus it overrides the method in SeekBar.java to avoid having two methods do the same on API>=16. Only downside: It needs target SDK to be >= 16 which should be the case in most apps nowadays.
public class ThumbSeekBar extends AppCompatSeekBar {
private Drawable thumb;
public ThumbSeekBar(Context context) {
super(context);
}
public ThumbSeekBar(Context context, AttributeSet attrs) {
super(context, attrs);
}
public ThumbSeekBar(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
}
#Override
public Drawable getThumb() {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) {
return super.getThumb();
}
return thumb;
}
#Override
public void setThumb(Drawable thumb) {
super.setThumb(thumb);
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.JELLY_BEAN) {
this.thumb = thumb;
}
}
}

Related

How to handle onclick events on the compound drawables of a TextInputEditText?

How can one detect click events on compound drawables of a TextInputEditText?
Use the following overriden version of TextInputEditText, and call setOnDrawableClickedListener.
You may fare better if you set your drawable at the end of the edit text than at the start, because the current version of TextInputLayout produces fairly ugly results when the drawable is at the start.
Sample layout is given further down. (Note the use of android:drawablePadding="10dp" particularly).
Code is for androidx, but you can backport to AppCompat trivially.
package com.twoplay.netplayer.controls;
import android.content.Context;
import android.graphics.Rect;
import android.graphics.drawable.Drawable;
import android.util.AttributeSet;
import android.view.MotionEvent;
import android.view.View;
import com.google.android.material.textfield.TextInputEditText;
public class TextInputEditTextEx extends TextInputEditText {
private OnDrawableClickedListener onDrawableClickedListener;
public TextInputEditTextEx(Context context) {
super(context);
init();
}
public TextInputEditTextEx(Context context, AttributeSet attrs) {
super(context, attrs);
init();
}
public TextInputEditTextEx(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
init();
}
private void init() {
setOnTouchListener(new OnTouchListener() {
private Rect hitBounds = new Rect();
#Override
public boolean onTouch(View v, MotionEvent event) {
float x = event.getX();
float y = event.getY();
int hitDrawable = -1;
if (x < getCompoundPaddingLeft())
{
hitDrawable = 0;
hitBounds.set(0,0,getCompoundPaddingLeft(),getHeight());
}
if (x > getWidth()-getCompoundPaddingRight())
{
hitDrawable = 2;
hitBounds.set(getCompoundPaddingRight(),0,getWidth(),getHeight());
}
if (hitDrawable != -1)
{
int action = event.getAction();
if (action == MotionEvent.ACTION_UP)
{
onDrawableClicked(hitDrawable,hitBounds);
}
return true;
}
return false;
}
});
}
private void onDrawableClicked(int i, Rect bounds) {
if (onDrawableClickedListener != null)
{
onDrawableClickedListener.onDrawableClicked(this,i,bounds);
}
}
public interface OnDrawableClickedListener {
void onDrawableClicked(View v, int drawable, Rect bounds);
}
public void setOnDrawableClickedListener(OnDrawableClickedListener listener)
{
this.onDrawableClickedListener = listener;
}
}
Sample layout:
<com.google.android.material.textfield.TextInputLayout
android:id="#+id/playlist_layout"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="#string/playlist_name" >
<com.twoplay.netplayer.controls.TextInputEditTextEx
android:id="#+id/playlist_text"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:inputType="textCapWords"
android:drawableEnd="#drawable/ic_more_horiz_black_24dp"
android:drawablePadding="10dp" />
</com.google.android.material.textfield.TextInputLayout>

How do I draw a drawable with its exact size in my custom view?

SOLVED: Solution below as answer.
I have a custom view with a TransitionDrawable and when I draw it in the onDraw() method it scales automatically to fill the whole parent layout, even when it's set in the xml to wrap_content. The picture is in mdpi and hdpi and my testing device (samsung galaxy s) I think it's no more than hdpi.
package com.adyrsoft.pronunciationtrainer;
import android.content.Context;
import android.graphics.Canvas;
import android.graphics.drawable.TransitionDrawable;
import android.util.AttributeSet;
import android.util.Log;
import android.view.View;
public class RecordButton extends View {
private static final String TAG = "RecordButton";
private TransitionDrawable mDrawable;
private boolean mActivated;
private OnClickListener mOnClickListenerInternal = new OnClickListener() {
#Override
public void onClick(View v) {
toggleState();
if(mOnClickListener != null) {
mOnClickListener.onClick(v);
}
}
};
private OnClickListener mOnClickListener = null;
public RecordButton(Context context) {
super(context);
init();
}
public RecordButton(Context context, AttributeSet attrib) {
super(context, attrib);
init();
}
public RecordButton(Context context, AttributeSet attrib, int defStyle) {
super(context, attrib, defStyle);
init();
}
public void setState(boolean activated) {
mActivated = activated;
if(mActivated){
mDrawable.startTransition(300);
}
else {
mDrawable.reverseTransition(300);
}
}
public void toggleState() {
if(mActivated) {
setState(false);
}
else {
setState(true);
}
}
#SuppressWarnings("deprecation")
private void init() {
mActivated = false;
mDrawable = (TransitionDrawable) getResources().getDrawable(R.drawable.btnrecord);
Log.d(TAG, "Drawable intrinsic width and height are: " +
Integer.toString(mDrawable.getIntrinsicWidth()) + " " +
Integer.toString(mDrawable.getIntrinsicHeight()));
mDrawable.setBounds(0,0,mDrawable.getIntrinsicWidth(), mDrawable.getIntrinsicHeight());
Log.d(TAG, "The bounds for the button are: "+mDrawable.getBounds().flattenToString());
super.setBackgroundDrawable(mDrawable);
setClickable(true);
super.setOnClickListener(mOnClickListenerInternal);
invalidate();
}
public void setOnClickListener(View.OnClickListener listener) {
mOnClickListener = listener;
}
protected void onDraw (Canvas canvas) {
super.onDraw(canvas);
}
}
What am I doing wrong?
Thanks.
After hours trying to understand how I should use the drawables in a custom view in order to be displayed in its original size, I've figured out how to do it.
First a few things that I didn't know but are a must is:
The background drawable should be left to the parent class to be
drawn when using View as the parent. If not, the TransitionDrawable can't be seen fading between pictures.
Only if I am going to draw on the background drawable I should override onDraw() and do the drawing there.
And the last but not less important is that I should override onMeasure() to specify the size of the view. If I don't do it, it will fill all the free space in the parent layout, as it was happening to me.
I've passed the TransitionDrawable to the parent class with setBackgroundDrawable() and since I wasn't drawing in the background drawable, I've removed the onDraw() method. Also I've implemented onMeasure() with a quick and dirty solution specifying the size of the picture I am drawing.
This is the final result:
public class RecordButton extends View {
private static final String TAG = "RecordButton";
private static final int DESIRED_WIDTH = 180;
private static final int DESIRED_HEIGHT = 66;
private TransitionDrawable mDrawable;
private Rect mViewRect;
private boolean mActivated;
private OnClickListener mOnClickListenerInternal = new OnClickListener() {
#Override
public void onClick(View v) {
toggleState();
if(mOnClickListener != null) {
mOnClickListener.onClick(v);
}
}
};
private OnClickListener mOnClickListener = null;
public RecordButton(Context context) {
this(context, null, 0);
}
public RecordButton(Context context, AttributeSet attrib) {
this(context, attrib, 0);
}
public RecordButton(Context context, AttributeSet attrib, int defStyle) {
super(context, attrib, defStyle);
init();
}
public void setState(boolean activated) {
mActivated = activated;
if(mActivated){
mDrawable.startTransition(300);
}
else {
mDrawable.reverseTransition(300);
}
}
public void toggleState() {
if(mActivated) {
setState(false);
}
else {
setState(true);
}
}
#SuppressWarnings("deprecation")
private void init() {
mActivated = false;
mDrawable = (TransitionDrawable) getResources().getDrawable(R.drawable.btnrecord);
setBackgroundDrawable(mDrawable);
setClickable(true);
super.setOnClickListener(mOnClickListenerInternal);
invalidate();
}
public void setOnClickListener(View.OnClickListener listener) {
mOnClickListener = listener;
}
#Override
protected void onMeasure(int m, int n) {
setMeasuredDimension(DESIRED_WIDTH, DESIRED_HEIGHT);
}
}

SeekBar with negative values on android [duplicate]

This question already has answers here:
How do I make a seekbar whose initail progress which is zero, starts in the middle
(5 answers)
Closed 9 years ago.
I am using a seek bar in my code with with two buttons to increment and decrement the values.The min and max range of seek bar should be from -30 to 480.
Can any one please suggest how to set the range in seek bar from -30 to 480.
Here's a class I use for this:
import android.content.Context;
import android.support.v7.appcompat.R;
import android.util.AttributeSet;
import android.widget.SeekBar;
/**
* Created by HeWhoWas on 5/10/13.
*/
public class NegativeSeekBar extends SeekBar {
protected int minimumValue = 0;
protected int maximumValue = 0;
protected OnSeekBarChangeListener listener;
public NegativeSeekBar(Context context){
super(context);
setUpInternalListener();
}
public NegativeSeekBar(Context context, AttributeSet attrs){
super(context, attrs);
setUpInternalListener();
}
public NegativeSeekBar(Context context, AttributeSet attrs, int defStyle){
super(context, attrs, defStyle);
setUpInternalListener();
}
public void setMin(int min){
this.minimumValue = min;
super.setMax(maximumValue - minimumValue);
}
public void setMax(int max){
this.maximumValue = max;
super.setMax(maximumValue - minimumValue);
}
#Override
public void setOnSeekBarChangeListener(OnSeekBarChangeListener listener){
this.listener = listener;
}
private void setUpInternalListener(){
super.setOnSeekBarChangeListener(new OnSeekBarChangeListener() {
#Override
public void onProgressChanged(SeekBar seekBar, int i, boolean b) {
if(listener != null){
listener.onProgressChanged(seekBar, minimumValue + i, b);
}
}
#Override
public void onStartTrackingTouch(SeekBar seekBar) {
if(listener != null)
listener.onStartTrackingTouch(seekBar);
}
#Override
public void onStopTrackingTouch(SeekBar seekBar) {
if(listener != null)
listener.onStopTrackingTouch(seekBar);
}
});
}
}

Add dynamic text over Android SeekBar thumb

I'm trying to make this custom SeekBar in Android 2.2 and everything I do seems to be wrong! I'm trying to display the value of the seekbar over the thumb image of the SeekBar. Does anybody have some experiences with this?
I have followed a different approach which provides more possibilities to customize the thumb. Final output will look like following:
First you have to design the layout which will be set as thumb drawable.
layout_seekbar_thumb.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="vertical">
<LinearLayout
android:layout_width="#dimen/seekbar_thumb_size"
android:layout_height="#dimen/seekbar_thumb_size"
android:background="#drawable/ic_seekbar_thumb_back"
android:gravity="center"
android:orientation="vertical">
<TextView
android:id="#+id/tvProgress"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="0"
android:textColor="#000000"
android:textSize="14sp" />
</LinearLayout>
</LinearLayout>
Here seekbar_thumb_size can be any small size as per your requirement. I have used 30dp here. For background you can use any drawable/icon of your choice.
Now you need this view to be set as thumb drawable so get it with following code:
View thumbView = LayoutInflater.from(YourActivity.this).inflate(R.layout.layout_seekbar_thumb, null, false);
Here I suggest to initialize this view in onCreate() so no need to inflate it again and again.
Now set this view as thumb drawable when seekBar progress is changed. Add the following method in your code:
public Drawable getThumb(int progress) {
((TextView) thumbView.findViewById(R.id.tvProgress)).setText(progress + "");
thumbView.measure(View.MeasureSpec.UNSPECIFIED, View.MeasureSpec.UNSPECIFIED);
Bitmap bitmap = Bitmap.createBitmap(thumbView.getMeasuredWidth(), thumbView.getMeasuredHeight(), Bitmap.Config.ARGB_8888);
Canvas canvas = new Canvas(bitmap);
thumbView.layout(0, 0, thumbView.getMeasuredWidth(), thumbView.getMeasuredHeight());
thumbView.draw(canvas);
return new BitmapDrawable(getResources(), bitmap);
}
Now call this method from onProgressChanged().
seekBar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
#Override
public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
// You can have your own calculation for progress
seekBar.setThumb(getThumb(progress));
}
#Override
public void onStartTrackingTouch(SeekBar seekBar) {
}
#Override
public void onStopTrackingTouch(SeekBar seekBar) {
}
});
Note: Also call getThumb() method when you initialize seekBar to initialize it with default value.
With this approach, you can have any custom view on progress change.
I assume you've already extended the base class, so you have something like:
public class SeekBarHint extends SeekBar {
public SeekBarHint (Context context) {
super(context);
}
public SeekBarHint (Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
}
public SeekBarHint (Context context, AttributeSet attrs) {
super(context, attrs);
}
}
Now you override the onDraw method with some of your own code. Insert the following:
#Override
protected void onDraw(Canvas c) {
super.onDraw(c);
}
Now, you want to draw some text near the thumb, but there isn't a convenient way to get the thumb's x-position. We just need a little math.
#Override
protected void onDraw(Canvas c) {
super.onDraw(c);
int thumb_x = ( (double)this.getProgress()/this.getMax() ) * (double)this.getWidth();
int middle = this.getHeight()/2;
// your drawing code here, ie Canvas.drawText();
}
seekBar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
#Override
public void onProgressChanged(SeekBar seekBar, int progress, boolean b) {
int val = (progress * (seekBar.getWidth() - 2 * seekBar.getThumbOffset())) / seekBar.getMax();
text_seekbar.setText("" + progress);
text_seekbar.setX(seekBar.getX() + val + seekBar.getThumbOffset() / 2);
}
#Override
public void onStartTrackingTouch(SeekBar seekBar) {
text_seekbar.setVisibility(View.VISIBLE);
}
#Override
public void onStopTrackingTouch(SeekBar seekBar) {
text_seekbar.setVisibility(View.GONE);
}
});
This worked for me
#Override
public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
int val = (progress * (seekBar.getWidth() - 2 * seekBar.getThumbOffset())) / seekBar.getMax();
_testText.setText("" + progress);
_testText.setX(seekBar.getX() + val + seekBar.getThumbOffset() / 2);
}
Hey I found another solution, seems simpler:
private void setText(){
int progress = mSeekBar.getProgress();
int max= mSeekBar.getMax();
int offset = mSeekBar.getThumbOffset();
float percent = ((float)progress)/(float)max;
int width = mSeekBar.getWidth() - 2*offset;
int answer =((int)(width*percent +offset - mText.getWidth()/2));
mText.setX(answer);
}
#Override
public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
setText();
mText.setText(""+progress);
}
This follow code aligns your TextView center to your SeekBar thumb center.
YOUR_TEXT_VIEW width must be wrap_content in xml.
Hope this code will help you.
#Override
public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
YOUR_TEXT_VIEW.setText(Integer.toString(progress));
double pourcent = progress / (double) seekBar.getMax();
int offset = seekBar.getThumbOffset();
int seekWidth = seekBar.getWidth();
int val = (int) Math.round(pourcent * (seekWidth - 2 * offset));
int labelWidth = YOUR_TEXT_VIEW.getWidth();
YOUR_TEXT_VIEW.setX(offset + seekBar.getX() + val
- Math.round(pourcent * offset)
- Math.round(pourcent * labelWidth/2));
}
I used this library to create drawable text view and put that drawable into thumb programmatically.
https://github.com/amulyakhare/TextDrawable
Code is something like this:
seekBar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
#Override
public void onStartTrackingTouch(SeekBar seekBar) {
}
#Override
public void onProgressChanged(SeekBar seekBar, int progress, boolean fromTouch) {
String dynamicText = String.valueOf(progress);
TextDrawable drawable = TextDrawable.builder()
.beginConfig()
.endConfig()
.buildRoundRect(dynamicText , Color.WHITE ,20);
seekBar.setThumb(drawable);
}
#Override
public void onStopTrackingTouch(SeekBar seekBar) {
}
});
Works not bad for me
there is a little hardcode)
please write improvements which smbd may has
import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Rect;
import android.support.v7.widget.AppCompatSeekBar;
import android.util.AttributeSet;
import android.util.TypedValue;
public class CustomSeekBar extends AppCompatSeekBar {
#SuppressWarnings("unused")
private static final String TAG = CustomSeekBar.class.getSimpleName();
private Paint paint;
private Rect bounds;
public String dimension;
public CustomSeekBar(Context context) {
super(context);
init();
}
public CustomSeekBar(Context context, AttributeSet attrs) {
super(context, attrs);
init();
}
public CustomSeekBar(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
init();
}
private void init(){
paint = new Paint();
paint.setColor(Color.WHITE);
paint.setStyle(Paint.Style.STROKE);
paint.setTextSize(sp2px(14));
bounds = new Rect();
}
#Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
String label = String.valueOf(getProgress()) + dimension;
paint.getTextBounds(label, 0, label.length(), bounds);
float x = (float) getProgress() * (getWidth() - 2 * getThumbOffset()) / getMax() +
(1 - (float) getProgress() / getMax()) * bounds.width() / 2 - bounds.width() / 2
+ getThumbOffset() / (label.length() - 1);
canvas.drawText(label, x, paint.getTextSize(), paint);
}
private int sp2px(int sp) {
return (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_SP, sp, getResources().getDisplayMetrics());
}
}
IMO best way is to do it through code. It is really not that scary and we are all programmers after all :)
class ThumbDrawable(context: Context) : Drawable() {
private val paint = Paint(Paint.ANTI_ALIAS_FLAG)
private val textPaint = Paint(Paint.ANTI_ALIAS_FLAG)
private val textBounds = Rect()
private var shadowColor = context.resources.getColor(R.color.wallet_screen_option_shadow)
private val size = context.resources.getDimensionPixelSize(R.dimen.thumbRadius).toFloat()
private val textSize = context.resources.getDimensionPixelSize(R.dimen.thumbTextSize).toFloat()
var progress: Int = 0
init {
textPaint.typeface = Typeface.createFromAsset(context.assets, "font/avenir_heavy.ttf")
val accentColor = context.resources.getColor(R.color.accent)
paint.color = accentColor
textPaint.color = accentColor
textPaint.textSize = textSize
paint.setShadowLayer(size / 2, 0f, 0f, shadowColor)
}
override fun draw(canvas: Canvas) {
Timber.d("bounds: $bounds")
val progressAsString = progress.toString()
canvas.drawCircle(bounds.left.toFloat(), bounds.top.toFloat(), size, paint)
textPaint.getTextBounds(progressAsString, 0, progressAsString.length, textBounds)
//0.6f is cause of the avenirs spacing, should be .5 for proper font
canvas.drawText(progressAsString, bounds.left.toFloat() - textBounds.width() * 0.6f, bounds.top.toFloat() - size * 2, textPaint)
}
override fun setAlpha(alpha: Int) {
}
override fun getOpacity(): Int {
return PixelFormat.OPAQUE
}
override fun setColorFilter(colorFilter: ColorFilter?) {
}
}
and in your seekbar implementation
class CustomSeekBar #JvmOverloads constructor(context: Context, attrs: AttributeSet? = null, defStyleAttr: Int = 0) :
SeekBar(context, attrs, defStyleAttr) {
init {
thumb = ThumbDrawable(context)
setPadding(0, 0, 0, 0);
}
override fun invalidate() {
super.invalidate()
if (thumb is ThumbDrawable) (thumb as ThumbDrawable).progress = progress
}
}
final result is something like this
I created this example to show how textview should be supported to different types of screen size and how to calculate the real position of Thumb because sometimes the position could be 0.
public class CustomProgressBar extends RelativeLayout implements AppCompatSeekBar.OnSeekBarChangeListener {
#BindView(R.id.userProgressBar)
protected AppCompatSeekBar progressSeekBar;
#BindView(R.id.textPorcent)
protected TextView porcent;
#BindView(R.id.titleIndicator)
protected TextView title;
public CustomProgressBar(Context context) {
super(context);
init();
}
public CustomProgressBar(Context context, AttributeSet attrs) {
super(context, attrs);
init();
}
private void init() {
LayoutInflater inflater = (LayoutInflater) getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
inflater.inflate(R.layout.custom_progressbar_view, this, true);
ButterKnife.bind(this);
setColors(R.color.green, R.color.progress_bar_remaining);
progressSeekBar.setPadding(0, 0, 0, 0);
progressSeekBar.setOnSeekBarChangeListener(this);
}
private void setPorcentTextViewPosition(float widthView) {
int width = CoreUtils.getScreenSize().x;
float xPosition = ((float) progressSeekBar.getProgress() / 100) * width;
float finalPosition = xPosition - (widthView / 2f);
if (width - xPosition < widthView) {
porcent.setX(width - widthView);
} else if (widthView < finalPosition) {
porcent.setX(finalPosition);
}
}
public void setColors(int progressDrawable, int remainingDrawable) {
LayerDrawable layer = (LayerDrawable) progressSeekBar.getProgressDrawable();
Drawable background = layer.getDrawable(0);
Drawable progress = layer.getDrawable(1);
background.setColorFilter(ContextCompat.getColor(getContext(), remainingDrawable), PorterDuff.Mode.SRC_IN);
progress.setColorFilter(ContextCompat.getColor(getContext(), progressDrawable), PorterDuff.Mode.SRC_IN);
}
public void setValues(int progress, int remaining) {
int value = (progress * remaining) / 100;
progressSeekBar.setMax(remaining);
porcent.setText(String.valueOf(value).concat("%"));
porcent.post(new Runnable() {
#Override
public void run() {
setPorcentTextViewPosition(porcent.getWidth());
}
});
progressSeekBar.setProgress(value);
}
public void setTitle(String title) {
this.title.setText(title);
}
#Override
public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
}
#Override
public void onStartTrackingTouch(SeekBar seekBar) {
}
#Override
public void onStopTrackingTouch(SeekBar seekBar) {
}
}
Add a TextView to your layout. Add onSeekBarChangeListener.
You will want precision so that the text is exactly in the middle of your seek bar thumb, you have to a little calculation. This is because the width of the text is different. Say, you want to show numbers from 0 to 150. Width of 188 will be different from 111. Because of this, the text you are showing will always tilt to some side.
The way to solve it is to measure the width of the text, remove that from the width of the seekbar thumb, divide it by 2, and add that to the result that was given in the accepted answer. Now you would not care about how large the number range. Here is the code:
override fun onProgressChanged(seekBar: SeekBar, progress: Int, fromUser: Boolean) {
val value = progress * (seekBar.width - 2 * seekBar.thumbOffset) / seekBar.max
label.text = progress.toString()
label.measure(0, 0)
val textWidth = label.measuredWidth
val firstRemainder = seekThumbWidth - textWidth
val result = firstRemainder / 2
label.x = (seekBar.x + value + result)
}

Automatic horizontal scroll in TextView

I have custom gallery.
Gallery represents items that are frame layout.
There are one imageView and textView above it.
If text in textView is too long, i need it to be scrolled automatically.
It's one line of text, and it's needed to be scrolled horizontally.
I've found this snippet of code:
TextView
android:text="Single-line text view that scrolls automatically"
android:singleLine="true"
android:ellipsize="marquee"
android:marqueeRepeatLimit ="marquee_forever"
android:focusable="true"
android:focusableInTouchMode="true"
android:scrollHorizontally="true"
android:layout_width="wrap_content"
android:layout_height="wrap_content"/>
It works in my test app with only one text view in it.
But it doesn't work in my gallery. Noting happens, text just stay still.
Any help?
Try this custom TextView class:
public class AutoScrollingTextView extends TextView {
public AutoScrollingTextView(Context context, AttributeSet attrs,
int defStyle) {
super(context, attrs, defStyle);
}
public AutoScrollingTextView(Context context, AttributeSet attrs) {
super(context, attrs);
}
public AutoScrollingTextView(Context context) {
super(context);
}
#Override
protected void onFocusChanged(boolean focused, int direction,
Rect previouslyFocusedRect) {
if (focused) {
super.onFocusChanged(focused, direction, previouslyFocusedRect);
}
}
#Override
public void onWindowFocusChanged(boolean focused) {
if (focused) {
super.onWindowFocusChanged(focused);
}
}
#Override
public boolean isFocused() {
return true;
}
}
and set the following XML attributes:
android:scrollHorizontally="true"
android:ellipsize="marquee"
android:marqueeRepeatLimit="marquee_forever"
This works beautifully in my dictionary apps where multiple entries may need to auto-scroll simultaneously to display complete content.
The marquee effect on a TextView is only designed to work when the view is focused or selected. The XML code you have tries to make the TextView focused all the time. Unfortunately, since only one view can be focused at any time, and since you have multiple views in the gallery, this approach will not work for you.
The easiest way to accomplish this otherwise is to make the TextViews always be selected. Multiple TextViews can hold the selected state at one time. Selection is meant to be used for an active element of an AdapterView, but still works outside of one. Firstly, remove the attributes modifying the focus from the XML and then just call TextView.setSelected(true) sometime after the view is initialised, e.g. in Activity.onCreate(Bundle) (there is no XML attribute for this). If you are supplying the views from an adapter, then you can call TextView.setSelected(true) during the getView() method after you inflate the view.
Here is an example project showing marquee working for multiple TextViews, and the behaviour inside a Gallery.
Try using ViewPager instead of gallery. This is available in android support packages. http://android-developers.blogspot.in/2011/08/horizontal-view-swiping-with-viewpager.html
I've tried everything, and finally came up with this. This works for me...hope that this will help you someday. Cheers.
package com.gui.custom_views;
import android.content.Context;
import android.graphics.Paint;
import android.graphics.Typeface;
import android.text.TextUtils;
import android.util.AttributeSet;
import android.view.Gravity;
import android.view.View;
import android.view.ViewGroup;
import android.view.animation.Animation;
import android.view.animation.LinearInterpolator;
import android.view.animation.TranslateAnimation;
import android.widget.LinearLayout;
import android.widget.ScrollView;
import android.widget.TextView;
import com.media_player.AndroidMediaPlayerActivity;
/**
* Custom Automatic Scrollable Text View
*
* #author Veljko Ilkic
*
*/
public class AutomaticScrollTextView extends LinearLayout {
// Context of application
Context context;
// TextView
private TextView mTextField1;
// Horizontal scroll
private ScrollView mScrollView1;
// Animation on start
private Animation mMoveTextOnStart = null;
// Out animation
private Animation mMoveText1TextOut = null;
// Duration of animation on start
private int durationStart;
// Duration of animation
private int duration;
// Pain for drawing text
private Paint mPaint;
// Text current width
private float mText1TextWidth;
/**
* Control the speed. The lower this value, the faster it will scroll.
*/
public static final int MS_PER_PX = 80;
/**
* Control the pause between the animations. Also, after starting this
* activity.
*/
public static final int PAUSE_BETWEEN_ANIMATIONS = 0;
private boolean mCancelled = false;
// Layout width
private int mWidth;
// Animation thread
private Runnable mAnimation1StartRunnable;
public AutomaticScrollTextView(Context context) {
super(context);
init(context);
this.context = context;
}
public AutomaticScrollTextView(Context context, AttributeSet attrs) {
super(context, attrs);
init(context);
this.context = context;
}
private void init(Context context) {
initView(context);
// init helper
mPaint = new Paint();
mPaint.setAntiAlias(true);
mPaint.setStrokeWidth(1);
mPaint.setStrokeCap(Paint.Cap.ROUND);
}
#Override
protected void onLayout(boolean changed, int l, int t, int r, int b) {
super.onLayout(changed, l, t, r, b);
mWidth = getMeasuredWidth();
// Calculate
prepare();
// Setup
setupText1Marquee();
}
#Override
public void setOnClickListener(OnClickListener l) {
super.setOnClickListener(l);
mTextField1.setOnClickListener(l);
}
// Method to finally start the marquee.
public void startMarquee() {
prepare();
prepareTextFields();
startTextField1Animation();
mCancelled = false;
}
private void startTextField1Animation() {
mAnimation1StartRunnable = new Runnable() {
public void run() {
mTextField1.setVisibility(View.VISIBLE);
mTextField1.startAnimation(mMoveTextOnStart);
}
};
postDelayed(mAnimation1StartRunnable, PAUSE_BETWEEN_ANIMATIONS);
}
public void reset() {
mCancelled = true;
if (mAnimation1StartRunnable != null) {
removeCallbacks(mAnimation1StartRunnable);
}
mTextField1.clearAnimation();
prepareTextFields();
mMoveTextOnStart.reset();
mMoveText1TextOut.reset();
mScrollView1.removeView(mTextField1);
mScrollView1.addView(mTextField1);
mTextField1.setEllipsize(TextUtils.TruncateAt.END);
invalidate();
}
public void prepareTextFields() {
mTextField1.setEllipsize(TextUtils.TruncateAt.END);
mTextField1.setVisibility(View.INVISIBLE);
expandTextView(mTextField1);
}
private void setupText1Marquee() {
// Calculate duration of animations
durationStart = (int) ((mWidth + mText1TextWidth) * MS_PER_PX);
duration = (int) (2 * mWidth * MS_PER_PX);
// On start animation
mMoveTextOnStart = new TranslateAnimation(0, -mWidth - mText1TextWidth,
0, 0);
mMoveTextOnStart.setDuration(durationStart);
mMoveTextOnStart.setInterpolator(new LinearInterpolator());
mMoveTextOnStart.setFillAfter(true);
// Main scrolling animation
mMoveText1TextOut = new TranslateAnimation(mWidth, -mWidth
- mText1TextWidth, 0, 0);
mMoveText1TextOut.setDuration(duration);
mMoveText1TextOut.setInterpolator(new LinearInterpolator());
mMoveText1TextOut.setFillAfter(true);
mMoveText1TextOut.setRepeatCount(Animation.INFINITE);
// Animation listeners
mMoveTextOnStart
.setAnimationListener(new Animation.AnimationListener() {
public void onAnimationStart(Animation animation) {
invalidate();
mTextField1.invalidate();
}
public void onAnimationEnd(Animation animation) {
if (mCancelled) {
return;
}
mTextField1.startAnimation(mMoveText1TextOut);
}
public void onAnimationRepeat(Animation animation) {
invalidate();
mTextField1.invalidate();
}
});
mMoveText1TextOut
.setAnimationListener(new Animation.AnimationListener() {
public void onAnimationStart(Animation animation) {
invalidate();
mTextField1.invalidate();
}
public void onAnimationEnd(Animation animation) {
if (mCancelled) {
return;
}
}
public void onAnimationRepeat(Animation animation) {
invalidate();
mTextField1.invalidate();
}
});
}
private void prepare() {
// Measure
mPaint.setTextSize(mTextField1.getTextSize());
mPaint.setTypeface(mTextField1.getTypeface());
mText1TextWidth = mPaint.measureText(mTextField1.getText().toString());
setupText1Marquee();
}
private void initView(Context context) {
setOrientation(LinearLayout.VERTICAL);
setLayoutParams(new LayoutParams(LayoutParams.FILL_PARENT,
LayoutParams.FILL_PARENT, Gravity.LEFT));
setPadding(0, 0, 0, 0);
// Scroll View 1
LayoutParams sv1lp = new LayoutParams(LayoutParams.FILL_PARENT,
LayoutParams.WRAP_CONTENT);
sv1lp.gravity = Gravity.CENTER_HORIZONTAL;
mScrollView1 = new ScrollView(context);
// Scroll View 1 - Text Field
mTextField1 = new TextView(context);
mTextField1.setSingleLine(true);
mTextField1.setEllipsize(TextUtils.TruncateAt.END);
mTextField1.setTypeface(null, Typeface.BOLD);
mScrollView1.addView(mTextField1, new ScrollView.LayoutParams(
mTextField1.getWidth(), LayoutParams.WRAP_CONTENT));
addView(mScrollView1, sv1lp);
}
public void setText1(String text) {
String temp = "";
if (text.length() < 10) {
temp = " " + text + " ";
} else {
temp = text;
}
mTextField1.setText(temp);
}
public void setTextSize1(int textSize) {
mTextField1.setTextSize(textSize);
}
public void setTextColor1(int textColor) {
mTextField1.setTextColor(textColor);
}
private void expandTextView(TextView textView) {
ViewGroup.LayoutParams lp = textView.getLayoutParams();
lp.width = AndroidMediaPlayerActivity.getScreenWidth();
textView.setLayoutParams(lp);
}
}
I came across this problem once and finally fixed the problem by calling .setFocus() on the textView.
Hi You have Tag in the xml file itself. And also use the Scrollview Property of FOCUS_DOWN in the java file ... Hope It helps to u ...
This code is working properly for me.
scrollview=(ScrollView)findViewById(R.id.scrollview1);
tb2.setTextSize(30);
tb2.setMovementMethod(new ScrollingMovementMethod());
scrollview.post(new Runnable() {
public void run() {
scrollview.fullScroll(View.FOCUS_DOWN);
}
});
public class ScrollingTextView extends TextView {
public ScrollingTextView(Context context, AttributeSet attrs,
int defStyle) {
super(context, attrs, defStyle);
}
public ScrollingTextView(Context context, AttributeSet attrs) {
super(context, attrs);
}
public ScrollingTextView(Context context) {
super(context);
}
#Override
protected void onFocusChanged(boolean focused, int direction,
Rect previouslyFocusedRect) {
if (focused) {
super.onFocusChanged(focused, direction, previouslyFocusedRect);
}
}
#Override
public void onWindowFocusChanged(boolean focused) {
if (focused) {
super.onWindowFocusChanged(focused);
}
}
#Override
public boolean isFocused() {
return true;
}
}
<com.test.autoscroll.ScrollingTextView
android:id="#+id/actionbar_title"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:paddingLeft="10dip"
android:paddingRight="10dip"
android:textSize="16dip"
android:textStyle="bold"
android:lines="1"
android:scrollHorizontally="true"
android:ellipsize="marquee"
android:text="autoscrollable textview without focus to textview...working...."
android:marqueeRepeatLimit="marquee_forever"
/>
Add this code to your own
findViewById(R.id.yourtextviewid).setSelected(true);
maybe your problem is fixed.

Categories

Resources