安卓课程十八 RadioButton单选按钮的使用
安卓课程十八 RadioButton单选按钮的使用:
activity_main.xml
RadioGroup android:id="@+id/idGroup" android:layout_width="wrap_content" android:layout_height="wrap_content" android:orientation="horizontal"> <RadioButton android:layout_width="wrap_content" android:id="@+id/radio_boy" android:layout_height="wrap_content" android:text="@string/sex_boy" android:checked="true" /> <RadioButton android:layout_width="wrap_content" android:layout_height="wrap_content" android:id="@+id/radio_girl" android:text="@string/sex_girl" /> </RadioGroup> <Button android:layout_width="fill_parent" android:layout_height="wrap_content" android:text="@string/selectBtn" android:id="@+id/selectBtn" />
MainActivity.java
import android.app.Activity; import android.os.Bundle; import android.view.Menu; import android.view.View; import android.widget.Button; import android.widget.RadioButton; import android.widget.RadioGroup; import android.widget.Toast; public class MainActivity extends Activity { private Button btn; private RadioGroup radioGroup; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); radioGroup = (RadioGroup) this.findViewById(R.id.idGroup); btn = (Button) this.findViewById(R.id.selectBtn); btn.setOnClickListener(new View.OnClickListener() { public void onClick(View v) { int radioCount = radioGroup.getChildCount(); RadioButton radioButton; String msg = ""; for (int i = 0; i < radioCount; i++) { radioButton =(RadioButton) radioGroup.getChildAt(i) ; if(radioButton.isChecked()){ msg = radioButton.getText().toString(); break; } } Toast.makeText(MainActivity.this,msg,Toast.LENGTH_SHORT).show(); } }); } }
相关推荐
huha 2020-10-16
xfcyhades 2020-11-20
sgafdsg 2020-11-04
Michael 2020-11-03
fengyeezju 2020-10-14
ziyexiaoxiao 2020-10-14
业余架构师 2020-10-09
OuNuo0 2020-09-29
moses 2020-09-22
Angelia 2020-09-11
qinxu 2020-09-10
刘炳昭 2020-09-10
Nostalgiachild 2020-09-07
Nostalgiachild 2020-08-17
leavesC 2020-08-14
一青年 2020-08-13
AndroidAiStudy 2020-08-07
ydc0 2020-07-30
绿豆饼 2020-07-28