I have an edittext having an image as drawable left with a non-editable prefixed editext but now i wanted to make it to support rtl. Despite my effort I am not able to support rtl.
My Custom class is as follows,
public class PrefixedEditText extends TextInputEditText {
private String mPrefix = "+"; // can be hardcoded for demo purposes
private Rect mPrefixRect = new Rect(); // actual prefix size
public PrefixedEditText(Context context, AttributeSet attrs) {
super(context, attrs);
}
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
getPaint().getTextBounds(mPrefix, 0, mPrefix.length(), mPrefixRect);
mPrefixRect.right += getPaint().measureText(" "); // add some offset
super.onMeasure(widthMeasureSpec, heightMeasureSpec);
}
@Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
canvas.drawText(mPrefix, super.getCompoundPaddingLeft(), getBaseline(), getPaint());
}
@Override
public int getCompoundPaddingLeft() {
return super.getCompoundPaddingLeft() + mPrefixRect.width();
}
}
My xml call of this class is as follows,
<cl.dd.ui.PrefixedEditText
style="@style/edittext"
android:id="@+id/etCode"
android:maxLength="3"
android:drawableLeft="@drawable/icon_phone_number"
android:drawableStart="@drawable/icon_phone_number"
android:minWidth="@dimen/dim_img_width"
android:hint="@string/s_login_code"
android:tag="@string/s_login_country_code"
android:inputType="number"/>
You would need to make sure that
supportsRtl
is set to true in yourAndroidManifest.xml
And set the
layoutDirection
tolocale
,inherit
orrtl
in your layout xml if you are targeting SDK 17+If your target SDK is below 17, you would have to create another res directory like
layout-ldrtl
orvalues-ldrtl
and maybe send an rtl flag to your custom view.Here is what I can suggest.
Instead of extending
TextInputEditText
, create a custom view based on a layout.The layout can be something like this:
Then, you can create a custom view, extending
RelativeLayout
with this layout. It will adapt to language direction changes.There are a few drawbacks - the resulting View won't be in the
EditText
class hierarchy, and using it in a lot of places can end up hurting the UI performance, since it introduces nested layouts, but at least the RTL part will be OK.To achieve the prefixed edit text with locale support just create a custom Edit Text and Draw the prefix as a drawable.
Refer the code snippet below:
To achieve RTL just put drawableStart instead of drawableLeft. Like this :
This will do the trick.