[英]Android - How to use a variable declared on an inner class?
I have this method: 我有这种方法:
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
AnimalWebService animalWebService = restAdapter.create(AnimalWebService.class);
Callback<List<Animal>> callback = new Callback<List<Animal>>() {
@Override
public void success(List<Animal> animals, Response response) {
if (animals == null) {
Context context = getApplicationContext();
CharSequence text = "No animals available!";
int duration = Toast.LENGTH_SHORT;
Toast toast = Toast.makeText(context, text, duration);
toast.show();
}
else {
ListAdapter theAdapter = new MyAdapter(getApplicationContext(), animals);
}
}
@Override
public void failure(RetrofitError retrofitError) {
return;
}
};
animalWebService.get(callback);
theListView.setAdapter(theAdapter);
}
In the end I have theListView.setAdapter(theAdapter);
最后,我有了theListView.setAdapter(theAdapter);
but theAdapter
is not recognized here since it was declared in an inner class. 但是由于在内部类中声明了theAdapter
,因此在此无法识别它。
How would I solve this? 我该如何解决? What are the best practices for this case when programming in Android? 在Android中进行编程时,针对这种情况的最佳做法是什么?
If you don't need a reference to theAdapter
in other parts of the Activity class, I would just update it from the callback: 如果您在Activity类的其他部分不需要引用theAdapter
,则只需从回调中对其进行更新:
Callback<List<Animal>> callback = new Callback<List<Animal>>() {
@Override
public void success(List<Animal> animals, Response response) {
if (animals == null) {
}
else {
ListAdapter theAdapter = new MyAdapter(getApplicationContext(), animals);
theListView.setAdapter(theAdapter);
}
}
@Override
public void failure(RetrofitError retrofitError) {
return;
}
};
This ensures that you are never calling setAdapter(null)
on the list view, which is good. 这样可以确保您永远不会在列表视图上调用setAdapter(null)
,这很好。 You should trigger events depending on the outcome of the callback: your call might fail (then failure
is called), or it could be returning an empty list. 你应该触发取决于回调的终点事件:您的通话可能会失败(当时failure
的叫法),或者它可以返回一个空列表。 In those cases we don't want the ListView to be attached to the adapter. 在这些情况下,我们不希望将ListView附加到适配器。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.