Android 同类(共享数据)

Android 同类(共享数据),android,textview,Android,Textview,我创建了一个AlertDialog(编辑文本),但后来我想将插入的值放入数组: void goToPage(){ AlertDialog.Builder alert = new AlertDialog.Builder(this); alert.setTitle("Title"); alert.setMessage("Message"); final EditText input = new EditText(this); alert.setView(in

我创建了一个AlertDialog(编辑文本),但后来我想将插入的值放入数组:

void goToPage(){

    AlertDialog.Builder alert = new AlertDialog.Builder(this);
    alert.setTitle("Title");
    alert.setMessage("Message");
    final EditText input = new EditText(this);
    alert.setView(input);
    alert.setPositiveButton("Ok", new DialogInterface.OnClickListener() {
    public void onClick(DialogInterface dialog, int whichButton) {
        String value = input.getText().toString();
        int value2 = Integer.parseInt(value);
    // Do something with value!
    }
    });
    alert.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
    public void onClick(DialogInterface dialog, int whichButton) {
    // Canceled.
    }
    });
    alert.show();           
}
在同一类中,我有以下数组:

array[20]
在同一个类中,我不能使用value2,因为它没有共享

如何将方法内的数据共享给整个类


谢谢

通过将数据传递到全局范围的变量中,可以将数据从方法共享给整个类。因此:

public class MyClass {
int num; //now this is global

//....everything else


}
确保您了解Java中scope的工作原理。在方法和循环中时,作用域会发生变化。但全局变量始终可以从类中的任何位置访问。在这样的情况下,此规则的例外情况变得很奇怪:

public class MyClass {
int num; //now this is global

    public MyClass(){
        num = 1;
    }
    public void access(int num) {
        num = 5;
    }
    public void printOut() {
        System.out.println(num);
    }

}
运行它:

MyClass something = new MyClass();
something.access(8);
something.printOut();

int的值仍然是
1
,因为
num
的另一个实例(在access()中)是本地的,这意味着全局
num
不知道它存在。他们是不同的。这就是
这个
关键字的作用。但我不会参与其中。你完全可以做这项研究:)

你可以在“onClick”函数中使用数组[20]