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();
}


在这里,为什么我不能在课堂上访问e1e2?错误; e1e2无法解析。

最佳答案

好:


person不是class,是method
您无法访问e1e2,因为它们是onCreate方法的本地variables


您应该将e1e2作为类的字段移动。

这样就可以了

// 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();
}

07-24 09:26