android 如何在形状右侧设置背景图片

How to set background image on the right hand side of a shape in android

我正在为 EditText 制作背景形状 - xml 下面:

<?xml version="1.0" encoding="UTF-8" ?> 
<shape xmlns:android="http://schemas.android.com/apk/res/android">
  <solid android:color="@color/WhiteSmoke"/> 
  <stroke android:width="1dp" android:color="@color/aadhaar_logo_brown" />   
  <padding android:left="2dp" android:top="2dp" android:right="2dp" android:bottom="2dp" /> 
  <corners android:topRightRadius="10dp" />
  <gradient android:startColor="@color/White" 
            android:centerColor="@color/White" 
            android:endColor="@color/White"
            android:angle="0"/>
</shape>

但是我需要在 EditText 的右侧有一个图像来指示必填字段。我尝试以编程方式添加图像,但图像未显示在运行时

((EditText) findViewById(R.id.txt_enduser_name)).setCompoundDrawables(null, null, getResources().getDrawable(R.drawable.ic_mandatory_text_field), null);

请帮忙

您需要为形状提供 "intrinsic size":

<shape xmlns:android="http://schemas.android.com/apk/res/android">
    ...
    <size android:height="20dp" android:width="20dp"/>
</shape>

然后,您可以将其设置为 drawableRight:

<EditText
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:drawableRight="@drawable/ic_mandatory_text_field"/>