Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

RTL support to custom editext for drawable left

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"/>
like image 636
Reprator Avatar asked Mar 11 '23 15:03

Reprator


1 Answers

You would need to make sure that supportsRtl is set to true in your AndroidManifest.xml

<application
    ...
    android:supportsRtl="true">

And set the layoutDirection to locale, inherit or rtl in your layout xml if you are targeting SDK 17+

<LinearLayout 
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    android:layoutDirection="locale">

If your target SDK is below 17, you would have to create another res directory like layout-ldrtl or values-ldrtl and maybe send an rtl flag to your custom view.

like image 173
Mostafa Gazar Avatar answered Apr 01 '23 19:04

Mostafa Gazar