因此,在Android/Java中,我需要访问一个全局变量,该变量是我在onClickListener
中的活动的onCreate
方法之上创建的EditText[]
。变量如下:
public class NCDTCPRelayActivity extends Activity {
final EditText[] relayLabelEdits = new EditText[n];
其中n
是另一个全局变量整数。
我的问题是,为了在onclickListener
中访问这些EditText
,我必须在onClickListener中进行final访问,但如果n的值改变了,我需要将relayLabelEdits
分配给一个新的EditText[]
,这是惯例。
以下是onClickListener
(该应用程序的主要部分是打开tcp套接字并通过WiFi控制中继,因此忽略套接字信息,并且那些指向relayLabelEdits
的System.out.println返回null,除非relayLabelEdits
变量是最终变量):
Button save = new Button(this);
save.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
EditText[] saveTargets = relayLabelEdits;
System.out.println("Direct: " + relayLabelEdits[0]);
System.out.println("first try " + saveTargets[0]);
//Creates string to create the database names on the fly
String relayToSave;
int myNum = 0;
try {
myNum = Integer.parseInt(portEditText.getText().toString());
} catch(NumberFormatException nfe) {
Toast toast = Toast.makeText(getBaseContext(), "The Port Number you entered must only contain numbers", Toast.LENGTH_LONG);
toast.show();
return;
}
System.out.println(ipAEditText.getText().toString());
cPanel.saveString("ipA", ipAEditText.getText().toString());
cPanel.saveInt("port", myNum);
for (int i = 0; i < n; i++) {
relayToSave = "relay" + (i+1);
System.out.println("HERE I AM");
System.out.println(relayLabelEdits[i]);
cPanel.saveString(relayToSave, relayLabelEdits[i].getText().toString());
//cPanel.saveString(relayToSave, "It worked");
System.out.println("HERE I AM");
}
if (cPanel.connect() == true){
createMainContainer();
setContentView(sView);
getRelayNames();
displayRelayNames();
updateButtonText();
}
else {
Toast toast = Toast.makeText(getBaseContext(), "Could Not Connect, check IP address and Port Number", Toast.LENGTH_LONG);
toast.show();
}
}
});
那么,关于如何访问onClickListener
中的EditText[]
而不使其成为最终版本,有什么想法吗?
为什么不让监听器成为外部的类,并将活动引用传递给它?