在代碼中,子view設置的屬性在viewGroup中無效的問題解決

<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>


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章