开发者

Pass data to OnItemClickListener?

DataAccess data = new DataAccess(db);
List<String> countries = data.getCountries();

setListAdapter(new ArrayAdapter<String>(this, R.layout.list_item, countries));

ListView lv = getListView();
lv.setTextFilterEnabled(true);

lv.setOnItemClickListener(new OnItemClickListener() {
  public void onItemClick(AdapterView<?> parent, View view,
      int position, long id) {

      // When clicked, show a toast with the TextView text
      Toast.makeText(getApplicationContext(), ((TextView) view).getText(),
        Toast.LENGTH_SHORT).show();
  }
});

How can I pass and access data variable fro开发者_Go百科m inside the onItemClick method?


make data final and you should be able to reference it from within onItemClick with data


final DataAccess data = new DataAccess(db);


lv.setOnItemClickListener(new OnItemClickListener() {
  public void onItemClick(AdapterView<?> parent, View view,
      int position, long id) {

        List<String> countries = data.getCountries();
   }
}

There is a reason why we do this. When you invoke "new OnItemClickListener()" you are essentially creating an anonymous inner class. The bytecode that gets generated do not actually translate into an inner class, the JVM has no idea about this inner class.

The Inner class files are translated into separate class files which has a combination of the Outer Class file and Inner Class File separated by the "$" sign. Since this case it is Anonymous, integers are used to identify the inner class.

OuterClass$1.class

In the above scenario, when you create a variable in the Outer class, then inner class will have no idea about it. However when you mark it as final, the inner class (actual class file) will get a hidden variable within it with a reference to the outer class variable.

data$data

Hope this helps.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜