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

来源:互联网 发布:seo怎么做优化 编辑:程序博客网 时间:2024/05/16 05:29

 问题描述:

     在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);}



0 0
原创粉丝点击