protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
TextView t = (TextView) findViewById(R.id.textView3);
EditText e1 = (EditText) findViewById(R.id.editText1);
EditText e2 = (EditText) findViewById(R.id.editText2);
}
private void person() {
String name = e1.getText();
String phone = e2.getText();
}
在这里,为什么我不能在课堂上访问
e1
和e2
?错误; e1
和e2
无法解析。 最佳答案
好:person
不是class,是method!
您无法访问e1
和e2
,因为它们是onCreate
方法的本地variables
您应该将e1
和e2
作为类的字段移动。
这样就可以了
// e1 and e2 are not anymore inside any method, so they will be fields of the class
EditText e1;
EditText e2;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
TextView t = (TextView) findViewById(R.id.textView3);
e1 = (EditText) findViewById(R.id.editText1);
e2 = (EditText) findViewById(R.id.editText2);
}
// person method can use them without problems
private void person()
{
String name = e1.getText();
String phone = e2.getText();
}