[英]how can i pass my instance variable througout my entire activity?
I am trying to make a custom list view adapter. 我正在尝试制作自定义列表视图适配器。 In my public void function I am trying to set the adapter.. (after make the list from the web 在我的public void函数中,我尝试设置适配器..(从网络上列出列表之后
This is in my onCreate(): 这是在我的onCreate()中:
rowItems = new ArrayList<RowItem>();
listView = (ListView) findViewById(R.id.list);
CustomListViewAdapter adapter = new CustomListViewAdapter(this,R.layout.activity_main, rowItems);
listView.setAdapter(adapter);
My question is: how can I make my custom listview adapter adapter variable available throughout my activity???? 我的问题是:如何在整个活动中使自定义listview适配器适配器变量可用?
Here is a snippet from when i set my names city and icon and i try to set my adapter 这是我设置名称城市和图标并尝试设置适配器时的摘录
item.setTitle(p.getString("name"));
item.setDesc(p.getString("city"));
item.setImageId(p.getString("icon"));
rowItems.add(item);
listView.setAdapter(adapter);
but eclipse can't find it. 但是蚀找不到它。 I even tried to recall the instance in the public void function with no luck.... 我什至没有运气就试图在公共无效函数中调用该实例。
Any suggestions? 有什么建议么?
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
new ReadWeatherJSONFeedTask().execute();
rowItems = new ArrayList<RowItem>();
listView = (ListView) findViewById(R.id.list);
CustomListViewAdapter adapter =
new CustomListViewAdapter(this,R.layout.activity_main, rowItems);
listView.setAdapter(adapter);
}
Move the declaration into a class field, like this: 将声明移到类字段中,如下所示:
public class MyActivity extends Activity{
CustomListViewAdapter adapter;
...
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
new ReadWeatherJSONFeedTask().execute();
rowItems = new ArrayList<RowItem>();
listView = (ListView) findViewById(R.id.list);
adapter = new CustomListViewAdapter(this,R.layout.activity_main, rowItems);
listView.setAdapter(adapter);
}
}
Class fields are accessible in all methods of a class. 类字段可在类的所有方法中访问。 It's all about "scope". 都是关于“范围”的。 Declaring the adapter inside onCreate
limits it's scope (it's visibility) to that method and classes declared within it. 在onCreate
内声明适配器将其范围(可见性)限制为该方法和在其中声明的类。
BTW, you don't say why you are trying to "reset" your adapter but usually, you should only set it once. 顺便说一句,您没有说为什么要“重置”适配器,但是通常,您应该只设置一次。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.