安卓app_sl3_14单选按钮示范
package com.example.sl3_14; import android.app.Activity; import android.os.Bundle; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.view.View.OnClickListener; import android.widget.Button; import android.widget.RadioButton; import android.widget.RadioGroup; import android.widget.Toast; import android.widget.RadioGroup.OnCheckedChangeListener; public class MainActivity extends Activity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); final RadioGroup sex=(RadioGroup) findViewById(R.id.radioGroup1); sex.setOnCheckedChangeListener(new OnCheckedChangeListener(){ @Override public void onCheckedChanged(RadioGroup group, int checkedId) { // TODO 自动生成的方法存根 RadioButton r=(RadioButton)findViewById(checkedId); String text="您的选择是:"+r.getText(); Toast toast=Toast.makeText(MainActivity.this, text, Toast.LENGTH_SHORT); toast.show(); } }); Button button=(Button)findViewById(R.id.button1); button.setOnClickListener(new OnClickListener(){ @Override public void onClick(View v) { // TODO 自动生成的方法存根 for(int i=0;i<sex.getChildCount();i++) { RadioButton r1=(RadioButton)sex.getChildAt(i); if(r1.isChecked()) { String ttx="点击提交按钮后的值:"+r1.getText(); Toast tt1=Toast.makeText(MainActivity.this, ttx, Toast.LENGTH_SHORT); tt1.show(); } } } }); } @Override public boolean onCreateOptionsMenu(Menu menu) { // Inflate the menu; this adds items to the action bar if it is present. getMenuInflater().inflate(R.menu.main, menu); return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { // Handle action bar item clicks here. The action bar will // automatically handle clicks on the Home/Up button, so long // as you specify a parent activity in AndroidManifest.xml. int id = item.getItemId(); if (id == R.id.action_settings) { return true; } return super.onOptionsItemSelected(item); } }
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="horizontal" tools:context="com.example.sl3_14.MainActivity" > <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:textSize="40px" android:text="性别:" /> <RadioGroup android:id="@+id/radioGroup1" android:orientation="horizontal" android:layout_width="wrap_content" android:layout_height="wrap_content" > <RadioButton android:id="@+id/radioButton1" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="男" /> <RadioButton android:id="@+id/radioButton2" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="女" /> </RadioGroup> <Button android:id="@+id/button1" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="提交" /> </LinearLayout>
欢迎讨论,相互学习。
cdtxw@foxmail.com