下面是我的 activity_main.xml 代码
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="16dp"
android:paddingTop="16dp"
android:paddingLeft="16dp"
android:paddingRight="16dp"
android:orientation="vertical">
<RadioGroup
android:layout_width="match_parent"
android:layout_height="300dp"
android:id="@+id/rgr">
<RadioButton
android:id="@+id/rb1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="1"
android:text="Mechanical" />
<RadioButton
android:id="@+id/rb2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="1"
android:text="Electrical" />
<RadioButton
android:id="@+id/rb3"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="1"
android:text="Civil" />
<RadioButton
android:id="@+id/rb4"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="1"
android:text="Computer Science" />
</RadioGroup>
</LinearLayout>
下面是 MainActivity.java 代码
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.Toast;
public class MainActivity extends AppCompatActivity
{ // https://www.youtube.com/watch?v=n7c3bIWcgZo
@Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
RadioGroup radioGroup = (RadioGroup)findViewById(R.id.rgr);
RadioButton radioButton1 = (RadioButton)findViewById(R.id.rb1);
RadioButton radioButton2 = (RadioButton)findViewById(R.id.rb2);
RadioButton radioButton3 = (RadioButton)findViewById(R.id.rb3);
RadioButton radioButton4 = (RadioButton)findViewById(R.id.rb4);
if(radioButton1.isChecked())
{
Toast.makeText(getApplicationContext(), radioButton1.getText(),Toast.LENGTH_LONG).show();
}
else if(radioButton2.isChecked())
{
Toast.makeText(getApplicationContext(), radioButton2.getText(),Toast.LENGTH_LONG).show();
}
else if(radioButton3.isChecked())
{
Toast.makeText(getApplicationContext(), radioButton3.getText(),Toast.LENGTH_LONG).show();
}
else if(radioButton4.isChecked())
{
Toast.makeText(getApplicationContext(), radioButton4.getText(),Toast.LENGTH_LONG).show();
}
}
现在,当我运行该应用程序时,单选按钮被选中,但是当我选择特定按钮时,吐司消息没有出现。
我也尝试过删除 radiogroup 并只保留单选按钮,但我仍然认为 isChecked() 功能没有执行。
请帮我解决这个问题。