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

今天做项目,公司的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);  
     } 



  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值