【学习笔记】Android 动态添加控件 getlayoutparams 为空的问题

 问题描述:

     在xml里面添加一个RadioGroup控件,在代码里面动态的给RadioGroup添加子控件RadioButton同时,给RadioButton之间设置间隔

 for (int i = 0; i < length; i++) {
			RadioButton radioButton = new RadioButton(getApplicationContext());
			radioButton.setText(Constants.feedbacks[i]);
			radioButton.setTextColor(Color.BLACK);
			radioButton.setButtonDrawable(R.drawable.xianiu_common_radio_btn_selector);
			LinearLayout.LayoutParams mLayoutParams = (LayoutParams) radioButton.getLayoutParams();
			mLayoutParams.setMargins( 0, 10, 0, 10);
			radioButton.setLayoutParams(mLayoutParams);
			radiogroup.addView(radioButton);
		}

       这段代码在运行时报错,因为 这句 mLayoutParams = (LayoutParams) radioButton.getLayoutParams();
mLayoutParams为null惊讶



经过一番查找才发现原来RadioButton只是被创建出来,还没有被添加到view中所以暂时获取不到LayoutParams

要先

edittext_radiogroup.addView(radioButton);

然后才可以

LinearLayout.LayoutParams mLayoutParams = (LayoutParams) radioButton.getLayoutParams();


改为:

for (int i = 0; i < length; i++) {
			RadioButton radioButton = new RadioButton(getApplicationContext());
			radioButton.setText(Constants.feedbacks[i]);
			radioButton.setTextColor(Color.BLACK);
			radioButton.setButtonDrawable(R.drawable.xianiu_common_radio_btn_selector);
			edittext_radiogroup.addView(radioButton);
			LinearLayout.LayoutParams mLayoutParams = (LayoutParams) radioButton.getLayoutParams();
			mLayoutParams.setMargins( 0, 10, 0, 10);
			radioButton.setLayoutParams(mLayoutParams);
		}


运行正常,问题解决了。再见


-------------------------------------------------可爱的分割线---------------------------------------------------------------------

前面写的只是添加几个RadioButton, 那么怎么添加点击事件呢?

RadioGroup的选中事件怎么写呢?

我们可以从

mGroup.setOnCheckedChangeListener(new OnCheckedChangeListener() {

@Override
public void onCheckedChanged(RadioGroup group, int checkedId) {


}

}

获取checkedId 。但是我们获取的checkedId有时候是很大的数字怎么办呢?

 解决办吧:

RadioButton radioButton = new RadioButton(getApplicationContext());
radioButton.setTag(i);

 给radioButton设置tag 

然后在选中事件里面获取tag 。

-----------------------------15.11.13编辑-----------------------------------------------

RadioButton  添加自定义图片之后,图片和文字之间的距离控制起来比较麻烦,因为API17之前的控制方法发生了变化。

直接上代码:

                             if(version >= 17){
						button.setPadding(20, 0, 10, 0);
					}else{
						button.setCompoundDrawablePadding(10);
					}



  • 2
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值