RadioButtton java代码实现左右带自定义的图片,并且控制字体与图片间距,同时控件长度对其功能。

来源:互联网 发布:mmd模型坐下姿势数据 编辑:程序博客网 时间:2024/06/06 21:06

今天做项目,公司的UI设计了一个这样的一个布局:


代码:

private RadioGroup mRadioGroup;private void initRadioButton(){mRadioGroup=(RadioGroup) findViewById(R.id.radio_group);int padding=40;int textSize=12;//spint 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);       } 



0 0
原创粉丝点击