Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

setCompoundDrawables EditText Text Overlapping

I'm Implementing a Drawable as text at the start of my EditText using setCompoundDrawables but I'm getting incorrect results. What I need is for my text to start after the Drawable when typing but in stead I'm getting this

enter image description here

I have a EditText In a layout defined 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 have to add a piece of text as a Drawable in the beginning of the EditText. So I convert Text to a 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 the drawable isn't defined as a resource.

like image 579
the-ginger-geek Avatar asked Jan 30 '14 07:01

the-ginger-geek


2 Answers

so setBounds in your Drawable's ctor, or override getIntrinsicWidth(), you will need to check which one works

like image 194
pskink Avatar answered Oct 25 '22 15:10

pskink


You can do like that

<EditText
        android:id="@+id/editText1"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:drawableLeft="@drawable/ic_launcher" >
like image 35
Rajan Avatar answered Oct 25 '22 16:10

Rajan