您可以将结束(右)填充应用于RadioButton
将可绘制对象向左移动。问题是应该应用多少填充?由于填充量将根据几个因素而变化,因此必须在代码中进行计算。(如果您有一个定义明确的环境并且知道文本长度不会改变,您可以在 XML 中设置填充。)
MainActivity.java
public class MainActivity extends AppCompatActivity {
private RadioButton mRadioButton;
private RadioButton mRadioButton2;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mRadioButton = findViewById(R.id.radioButton);
mRadioButton2 = findViewById(R.id.radioButton2);
RadioGroup rg = findViewById(R.id.radioGroup);
rg.post(new Runnable() {
@Override
public void run() {
moveDrawable(mRadioButton);
moveDrawable(mRadioButton2);
}
private void moveDrawable(RadioButton radioButton) {
// Get the drawables for this radio button. If the right drawable is not null
// then we need to move it to the end of the text.
Drawable[] drawables = radioButton.getCompoundDrawables();
if (drawables[2] != null) {
// Compute how much end padding to apply to get the drawable beside the text.
int textLen = (int) radioButton.getPaint().measureText((String) radioButton.getText());
// 4dp between the text and the drawable just to separate them a little.
int drawableLeftPadding =
(int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP,
4, getResources().getDisplayMetrics());
int paddingEnd = radioButton.getWidth() -
(radioButton.getCompoundPaddingLeft() + +textLen + drawables[2].getIntrinsicWidth())
- drawableLeftPadding;
radioButton.setPadding(0, 0, paddingEnd, 0);
}
}
});
}
}
activity_main.xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="@android:color/darker_gray"
android:orientation="vertical"
android:padding="16dp">
<RadioGroup
android:id="@+id/radioGroup"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical">
<RadioButton
android:id="@+id/radioButton"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="@android:color/holo_blue_light"
android:drawableEnd="@drawable/ic_insert_emoticon_yellow_24dp"
android:text="Test Test Test Test Test " />
<RadioButton
android:id="@+id/radioButton2"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="@android:color/holo_red_light"
android:drawableEnd="@drawable/ic_insert_emoticon_yellow_24dp"
android:text="Test" />
<RadioButton
android:id="@+id/radioButton3"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="@android:color/holo_blue_light"
android:drawableEnd="@drawable/ic_insert_emoticon_yellow_24dp"
android:text="Test" />
</RadioGroup>
</LinearLayout>