Android 中获取RadioButton选中值的两种方式

布局代码如下:



    

        

        

        

        

    

第一种方法:

   /**
     * 初始化监听
     */
    private void initListener(){
        btnConfirm.setOnClickListener(this);

        //RadioGroup选取值的方法一
        rgSelect.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(RadioGroup radioGroup, int i) {
                selectRadioButton();
            }
        });
    }

    /**
     * 获取RadioButton选中值
     */
    private void selectRadioButton() {
        RadioButton rb = (RadioButton)getActivity().findViewById(rgSelect.getCheckedRadioButtonId());
        CharSequence text = rb.getText();

    }

第二种方法:

 //RadioGroup选取值的方法二
            for(int i = 0 ;i < rgSelect.getChildCount();i++){
                RadioButton rb = (RadioButton)rgSelect.getChildAt(i);
                if(rb.isChecked()){
                    break;
                }
            }

完整代码:

public class UserFeedbackFragment extends BaseFragment {

    private static final String TAG = UserFeedbackFragment.class.getSimpleName();

    private RadioGroup rgSelect;
    private RadioButton rbProblem;
    private RadioButton rbSuggestion;
    private LinearLayout lltContentView;
    private EditText etTitle;
    private EditText etContactInfo;
    private EditText etContent;
    private Button btnConfirm;

    @Override
    protected int getLayoutResId() {
        return R.layout.fragment_user_feedbak;
    }

    @Override
    protected void initFragmentView() {
        rgSelect = xFindViewById(R.id.rg_select);
        rbProblem = xFindViewById(R.id.rb_problem);
        rbSuggestion = xFindViewById(R.id.rb_suggestion);
        btnConfirm = xFindViewById(R.id.btn_confirm);
    }

    @Override
    protected void initFragmentOperate() {

    }

    /**
     * 初始化监听
     */
    private void initListener(){
        btnConfirm.setOnClickListener(this);

        //RadioGroup选取值的方法一
        rgSelect.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(RadioGroup radioGroup, int i) {
                selectRadioButton();
            }
        });
    }

    /**
     * 获取RadioButton选中值
     */
    private void selectRadioButton() {
        RadioButton rb = (RadioButton)getActivity().findViewById(rgSelect.getCheckedRadioButtonId());
        CharSequence text = rb.getText();

    }


    @Override
    public void onClick(View v) {
        super.onClick(v);
        if (v.equals(btnConfirm)){

            //RadioGroup选取值的方法二
            for(int i = 0 ;i < rgSelect.getChildCount();i++){
                RadioButton rb = (RadioButton)rgSelect.getChildAt(i);
                if(rb.isChecked()){
                    break;
                }
            }

        }
    }
}

你可能感兴趣的:(Android 中获取RadioButton选中值的两种方式)