[英]Accessing variables from another class Android Studio
I'm new to android development and I'm wondering how this can be done. 我是android开发的新手,我想知道如何做到这一点。 I have a class named ListDeadlines with variables such as
我有一个名为ListDeadlines的类,其中包含诸如
public ArrayList<String> arrayList;
public ArrayAdapter<String> adapter;
public EditText txtInput;
I want to be able to access these variables in a different class. 我希望能够在其他类中访问这些变量。 I have tried it like this, however I get the fallowing error on my
lst.txtInput lst.arrayList lst.adapter
saying Variable 'lst' is accessed from within inner class, needs to be declared final.
我已经这样尝试过,但是我在
lst.txtInput lst.arrayList lst.adapter
上收到了错误lst.txtInput lst.arrayList lst.adapter
说Variable 'lst' is accessed from within inner class, needs to be declared final.
Anyone got any ideas on how to access variables in another class. 任何人都对如何访问另一个类中的变量有任何想法。
ListDeadlines lst= new ListDeadlines();
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
lst.txtInput=(EditText)findViewById(R.id.txtinput);
Button btAdd=(Button)findViewById(R.id.btnAdd);
btAdd.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
String newItem = lst.txtInput.getText().toString();
lst.arrayList.add(newItem);
lst.adapter.notifyDataSetChanged();
;
}
});
What you're trying to do here is access the variable lst from within an anonymous inner class in the same scope as lst. 您要在此处执行的操作是从与lst相同作用域的匿名内部类中访问变量lst。 The anonymous inner class is your
new View.OnClickListener
. 匿名内部类是您的
new View.OnClickListener
。 The rules for doing this in Java require that you declare lst as final
so that the inner class can be certain that lst will not change when it eventually executes. Java中执行此操作的规则要求您将lst声明为
final
以便内部类可以确定lst在最终执行时不会改变。 So, you can declare your lst like this: 因此,您可以像这样声明您的第一个:
final ListDeadlines lst= new ListDeadlines();
Or you can make lst a member of the enclosing class that contains the method where it's currently defined. 或者,您可以使lst成为包含类的成员,该类包含当前定义的方法。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.