已经在XML中设置了一个radioButton为选中,但是当运行起来什么都不选择,用默认的情况,点击按钮会报空指针,解决办法,初始化把radioButton根据ID设置成男,然后setChecked(true);就可以了
activity_main.xml
MainActivity
package com.example.radiobuttontest2;import android.os.Bundle;import android.R.integer;import android.app.Activity;import android.view.Menu;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;public class MainActivity extends Activity { private RadioGroup radioGroup; private Button button; private RadioButton radioButton; int selectedRadioButtonId; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); radioButton = (RadioButton) findViewById(R.id.male);//就是这2句,解决空指针 radioButton.setChecked(true); radioGroup = (RadioGroup) findViewById(R.id.radiogroup); button = (Button) findViewById(R.id.button); button.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { selectedRadioButtonId = radioGroup.getCheckedRadioButtonId(); radioButton = (RadioButton) findViewById(selectedRadioButtonId); Toast.makeText(MainActivity.this, "你选择的性别是"+radioButton.getText(), Toast.LENGTH_SHORT).show(); } }); } }