今天做项目,公司的UI设计了一个这样的一个布局:
代码:
private RadioGroup mRadioGroup;
private void initRadioButton(){
mRadioGroup=(RadioGroup) findViewById(R.id.radio_group);
int padding=40;
int textSize=12;//sp
int count=4;
RadioButton[] testButtons=new RadioButton[count];
float maxTextLength=0;//最长的文本文档,但是不能换行,换行计算会有问题。
Paint paint=new Paint();
paint.setTextSize(sp2px(textSize));//设置当前文字的大小
float[] itemTextLength=new float[count];//记录每一个RadioButton的文字长度。
for(int i=0;i<count;i++){
testButtons[i]=new RadioButton(this);
String content="啦啦";
for(int j=0;j<i;j++){
content+=content;
}
itemTextLength[i]=paint.measureText(content);
if(maxTextLength<itemTextLength[i]){
maxTextLength=itemTextLength[i];
}
testButtons[i].setText(content);
testButtons[i].setTextSize(TypedValue.COMPLEX_UNIT_SP, textSize);//这里设置文本的字体大小
testButtons[i].setButtonDrawable(ContextCompat.getDrawable(this, R.drawable.ic_launcher));
testButtons[i].setPadding(padding, 0, 0, 0);//这里设置的是文本距离左上右下的图片的距离,这里设置了距离左侧图片距离。
testButtons[i].setCompoundDrawablesWithIntrinsicBounds(null, null, ContextCompat.getDrawable(this,R.drawable.radio_button), null);//not set left because this will have default radio button.
//这里设置图片可以自己选择上下左右,但是左侧最好不选择,原因是其本身默认的图标在左侧,如果设置后面不设置setButtonDrawable会导致最左侧出现默认图标。建议在后面设置。如果要设置,建议后面添加设置:setButtonDrawable(ContextCompat.getDrawable(this,android.r.color.transparent));设置透明。
}
for(int i=0;i<count;i++){
float maxThenThisTextLength=maxTextLength-itemTextLength[i];
testButtons[i].setCompoundDrawablePadding((int) (padding+maxThenThisTextLength));//这里是设置距离右边的图片距离。
mRadioGroup.addView(testButtons[i]);
}
}
private int sp2px(float spValue) {
final float fontScale =getResources().getDisplayMetrics().scaledDensity;
return (int) (spValue * fontScale + 0.5f);
}