在OnCreate()中创建对象RadioGroup时,稍后在另一个函数中调用此对象时,它将显示错误“无法解析此符号”
这是Java代码
MainActivity.java
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
RadioGroup group1 = (RadioGroup)findViewById(R.id.que1_rG);
RadioGroup group2 = (RadioGroup)findViewById(R.id.que2rG);
RadioGroup group3 = (RadioGroup)findViewById(R.id.que3rG);
RadioGroup group4 = (RadioGroup)findViewById(R.id.que4rG);
RadioGroup group5 = (RadioGroup)findViewById(R.id.que5rG);
RadioGroup group6 = (RadioGroup)findViewById(R.id.que6rG);
RadioGroup group7 = (RadioGroup)findViewById(R.id.que7rG);
RadioGroup group8 = (RadioGroup)findViewById(R.id.que8rG);
RadioGroup group9 = (RadioGroup)findViewById(R.id.que9rG);
RadioGroup group10 = (RadioGroup)findViewById(R.id.que10rG);
}
public void submitButton(View view)
{
int checkedRadio1= group1.getCheckedRadioButtonId();
Toast.makeText(this,"Score is : " + score,Toast.LENGTH_SHORT);
Log.v("MainActivity","Score is " + score);
score = 0;
}
答案 0 :(得分:1)
您无法解析符号的原因是,您尚未在课程级别声明RadioGroup group1
。由于您已经在onCreate
中进行了声明和分配,因此其范围仅限于onCreate()
。要使用其他方法进行访问,请使其成为类成员。
声明RadioGroup group1
为类成员,如下所示:
public class MainAcivity extends Activity{
private RadioGroup group1;
//Declare other RadioGroup group2,group3...group 10. if you intend
//to access them outside of onCreate()
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
group1 = (RadioGroup)findViewById(R.id.que1_rG);
...
}
public void submitButton(View view) {
int checkedRadio1= group1.getCheckedRadioButtonId();
Toast.makeText(this,"Score is : " + score,Toast.LENGTH_SHORT).show();
Log.v("MainActivity","Score is " + score);
score = 0;
}
}
注意:
同样的情况也适用于您希望在RadioGroup
之外访问的任何其他onCreate()
。
在尝试显示show()
时,您也缺少对Toast
方法的调用。不致电show()
,将不会显示Toast消息。
代替
Toast.makeText(this,"Score is : " + score,Toast.LENGTH_SHORT)
使用
Toast.makeText(this,"Score is : " + score,Toast.LENGTH_SHORT).show()
答案 1 :(得分:1)
在班级声明单选按钮。您正在函数级别使用veriable,因此不能在函数之外使用该变量。
private RadioGroup group1, group2, group3, group4, group5, group6, group7,group8,group9,group10;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
group1 = (RadioGroup)findViewById(R.id.que1_rG);
group2 = (RadioGroup)findViewById(R.id.que2rG);
group3 = (RadioGroup)findViewById(R.id.que3rG);
group4 = (RadioGroup)findViewById(R.id.que4rG);
group5 = (RadioGroup)findViewById(R.id.que5rG);
group6 = (RadioGroup)findViewById(R.id.que6rG);
group7 = (RadioGroup)findViewById(R.id.que7rG);
group8 = (RadioGroup)findViewById(R.id.que8rG);
group9 = (RadioGroup)findViewById(R.id.que9rG);
group10 = (RadioGroup)findViewById(R.id.que10rG);
}
public void submitButton(View view)
{
int checkedRadio1= group1.getCheckedRadioButtonId();
Toast.makeText(this,"Score is : " + score,Toast.LENGTH_SHORT);
Log.v("MainActivity","Score is " + score);
score = 0;
}