當前位置:編程學習大全網 - 源碼下載 - 如何獲取RadioGroup中RadioButton的值

如何獲取RadioGroup中RadioButton的值

1,獲取RadioGroup控件:

RadioGroup radioGroup = (RadioGroup)findViewById(R.id.myRadioGroup);

2,獲取RadioButton控件;

RadioButton radioButton = (RadioButton)findViewById(radioGroup.getCheckedRadioButtonId());

3,獲取選中的radio的值:

String text = radioButton.getText().toString();

4,為radioGroup添加監聽事件,用來監聽組件內部的事件響應:

radioGroup.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {

@Override

public void onCheckedChanged(RadioGroup group, int checkedId) {

//在這個函數裏面用來改變選擇的radioButton的數值,以及與其值相關的 //任何操作,詳見下文

selectRadioBtn();

}

})

5,在onCreat中需要初始化上面的四條信息;

6,整體的使用樣例:

布局文件xml中的內容:

<RadioGroup

android:id="@+id/sex_group"

android:layout_width="match_parent"

android:layout_height="wrap_content">

<RadioButton

android:id="@+id/male"

android:layout_width="wrap_content"

android:layout_height="wrap_content"

android:checked="true"

android:text="男"/>

<RadioButton

android:id="@+id/female"

android:layout_width="wrap_content"

android:layout_height="wrap_content"

android:text="女"/>

</RadioGroup>

代碼實現:

private RadioGroup mSex_group;

private RadioButton mMale;

private RadioButton mFemale;

private String sexName;

mSex_group = (RadioGroup) findViewById(R.id.sex_group);

mMale = (RadioButton) findViewById(R.id.male);

mFemale = (RadioButton) findViewById(R.id.female);

mSex_group.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {

@Override

public void onCheckedChanged(RadioGroup group, int checkedId) {

if (mMale.getId() == checkedId) {

sexName = mMale.getText().toString();

} else if (mFemale.getId() == checkedId) {

sexName = mFemale.getText().toString();

}

}

});

  • 上一篇:請問在c++中如何進行文件的輸入輸出以及讀入?
  • 下一篇:如何更新及替換ViewPager中的Fragment
  • copyright 2024編程學習大全網