您的位置:首页 > 编程语言

在代码中,子view设置的属性在viewGroup中无效的问题解决

2016-01-11 15:08 369 查看
<span style="font-family:SimHei;font-size:14px;">                RadioGroup myRadioGroup = new RadioGroup(this);
		myRadioGroup.setLayoutParams(new LayoutParams(
				LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT));
		myRadioGroup.setOrientation(LinearLayout.HORIZONTAL);
		for (int i = 0; i < 3; i++) {
			RadioButton mRadioButton = new RadioButton(this);
			LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(
					0, 100);
			params.weight = 1.0f;
			params.gravity = Gravity.CENTER;
			mRadioButton.setLayoutParams(params);
			mRadioButton.setText(""+i);
			myRadioGroup.addView(mRadioButton);
		}</span>

需求是创建3个横向显示的单选按钮,并且这三个按钮的宽度平分屏幕宽度,上面的写法是错误的,设置的params属性并不会有效果,因为params中的一些属性是相对于父布局设置的,例如这个params.weight = 1.0f; 而此时这个单选按钮并没有一个父布局,所以应该改成:

<span style="font-family:SimHei;font-size:14px;">for (int i = 0; i < 3; i++) {
			RadioButton mRadioButton = new RadioButton(this);
			myRadioGroup.addView(mRadioButton);
			LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(
					0, 100);
			params.weight = 1.0f;
			params.gravity = Gravity.CENTER;
			mRadioButton.setLayoutParams(params);
			mRadioButton.setText(""+i);
		}</span>
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: