SetCompoundDrawables Drag Text EditText

I am implementing Drawable as text at the beginning of my EditText using setCompoundDrawables , but I setCompoundDrawables getting the wrong results. I need my text to start after Drawable when typing, but instead I get this

enter image description here

I have an EditText in a layout like this

 <?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:id="@+id/control" android:layout_width="fill_parent" android:layout_height="wrap_content" android:orientation="horizontal" android:paddingLeft="4dp" > <EditText android:id="@+id/field" style="@style/TextField" android:inputType="number" /> </LinearLayout> 

I need to add the text as Drawable at the beginning of the EditText . Therefore, I convert text to Drawable using this class

 public class TextDrawable extends Drawable { private final String text; private final Paint paint; public TextDrawable(String text) { this.text = text; this.paint = new Paint(); paint.setColor(Color.parseColor("#009999")); paint.setTextSize(30); paint.setAntiAlias(true); paint.setTextAlign(Paint.Align.LEFT); } @Override public void draw(Canvas canvas) { canvas.drawText(text, 0, 6, paint); } @Override public void setAlpha(int alpha) { paint.setAlpha(alpha); } @Override public void setColorFilter(ColorFilter cf) { paint.setColorFilter(cf); } @Override public int getOpacity() { return PixelFormat.TRANSLUCENT; } } 

And I implement it here

 final EditText field = (EditText) widget.findViewById(R.id.field); field.setCompoundDrawables(new TextDrawable(this.label), null, null, null); field.setText(this.value); 

Am I doing something wrong?

EDIT

I tried using this method field.setCompoundDrawablesWithIntrinsicBounds(R.drawable.my_drawable, 0, 0, 0); , and it works, but obviously I can't use it because drawable is not defined as a resource.

+6
source share
3 answers

so set Bounds to your Drawable ctor or override getIntrinsicWidth (), you will need to check which one works

+3
source

You can do it

 <EditText android:id="@+id/editText1" android:layout_width="match_parent" android:layout_height="wrap_content" android:drawableLeft="@drawable/ic_launcher" > 
+1
source

Try to do it -

 field.setCompoundDrawablesWithIntrinsicBounds(new TextDrawable(this.label), null, null, null); 

You have to set boundaries.

0
source

All Articles