实现Android单选框的监听
程序员文章站
2022-05-25 08:04:02
...
<?xml version="1.0" encoding="utf-8"?>
<RadioGroup
android:id="@+id/gp"
android:layout_width="match_parent"
android:layout_height="200dp"
android:orientation="horizontal">
<RadioButton
android:id="@+id/nan"
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_weight="1"
android:text="男" />
<RadioButton
android:id="@+id/nv"
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_weight="1"
android:text="女" />
</RadioGroup>
以下是java文件
package part1.bw.com.test02;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.Toast;
public class test7Activity extends AppCompatActivity {
RadioGroup gp;
RadioButton nan;
RadioButton nv;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_test7);
nan=findViewById(R.id.nan);
nv=findViewById(R.id.nv);
gp=findViewById(R.id.gp);
gp.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
@Override
public void onCheckedChanged(RadioGroup group, int checkedId) {
if(checkedId==nan.getId()){
Toast.makeText(test7Activity.this, "男", Toast.LENGTH_SHORT).show();
}else{
Toast.makeText(test7Activity.this, "女", Toast.LENGTH_SHORT).show();
}
}
});
}
}