单选按钮的操作

布局文件main.xml




    

    
        
        
    



定义Activity程序

package com.example.lenovo.myapplication;

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.TextView;

public class Sex extends AppCompatActivity {

        private TextView show ;
        private RadioGroup sex ;
        private RadioButton male ;
        private RadioButton female ;

        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_main);
            this.show = (TextView) super.findViewById(R.id.show);
            this.sex = (RadioGroup) super.findViewById(R.id.sex);
            this.male = (RadioButton) super.findViewById(R.id.male);
            this.female = (RadioButton) super.findViewById(R.id.female);
            this.sex.setOnCheckedChangeListener(new OnCheckedChangeListenerImpl());
        }

        private class OnCheckedChangeListenerImpl implements RadioGroup.OnCheckedChangeListener {
            @Override
        public void onCheckedChanged(RadioGroup group, int checkedId) {
                String temp = null;
                if (Sex.this.male.getId()==checkedId){
                    temp = Sex.this.male.getText().toString();
                }
                if (Sex.this.female.getId()==checkedId){
                    temp = Sex.this.female.getText().toString();
                }
                Sex.this.show.setText("你的性别是:"+temp);
            }
        }
}

你可能感兴趣的:(单选按钮的操作)