Android 分析监听器上的参数position和id(二)

二、使用方式

  分两种场景,以代码的形式来展示使用方式,以下均选中第2行:

  1.SimpleAdapter
模拟数据,其中_id类似于数据库中的主键,主键名一定要带有”_id”,Android好这口。虽然不是从数据库获取的数据,但最好也要遵从这种习惯。

ArrayList> classic = new ArrayList>();     HashMap englishMap = new HashMap();     englishMap.put(“classic_id”,1l);  englishMap.put(“name”,lileilei);   englishMap.put(“gender”,male);   englishMap.put(“classic _id”,2l);   englishMap.put(“name”,hanmeimei);   englishMap.put(“gender”,female);   englishMap.put(“classic _id”,3l);   englishMap.put(“name”,poly);   englishMap.put(“gender”,male);     //创建SimpleAdater     SimpleAdapter simpleAdapter = new SimpleAdapter(this, data, R.layout.classic,new String[] { " classic _id", "name", "age" }, new int[] {R.id.id_text, R.id.name_text, R.id.age_text });     //设置监听器     ListView lv = this.findViewById(R.id.listview);     lv.setAdapter(simpleAdapter);   lv.setOnItemClickListener(new OnItemClickListener() {     @Override     public void onItemClick(AdapterView parent, View view,int position, long id) {     Log.i(LOG_TAG, "position:" + position);//输出1   Log.i(LOG_TAG, "id:" + id);//输出1   Log.i(LOG_TAG, "item class : "+ ((ListView) parent).getItemAtPosition(position).getClass().getSimpleName());//输出item class : HashMap     //由于上面第三条日志信息输出的类型为HashMap,所以采用HashMap的方式获取数据。     HashMap englishMap = (HashMap) ((ListView) parent).getItemAtPosition(position);     if (englishMap!= null && englishMap.size()> 0) {     //做其他操作     }   }   });

2. CursorAdapter

 

//从数据库中获取数据,同样,返回的Cursor中必须含有”_id”的字段。     Cursor cursor = .....;//写一个查询数据的方法并返回一个Cursor对象;     //创建SimpleCursorAdapter     SimpleCursorAdapter simpleCursorAdapter = new SimpleCursorAdapter(this,R.layout.person, cursor, new String[] { " classic _id ", "name", "age" },new int[] { R.id.id_text, R.id.name_text, R.id.age_text });     //设置监听器     ListView lv = this.findViewById(R.id.listview);     lv.setAdapter(simpleCursorAdapter);   lv.setOnItemClickListener(newOnItemClickListener() {     @Override     public void onItemClick(AdapterView parent, View view,int position, long id) {     Log.i(LOG_TAG, "position:" + position);//输出1  Log.i(LOG_TAG, "id:" + id);//输出2   Log.i(LOG_TAG, "item class : "+ ((ListView) parent).getItemAtPosition(position).getClass().getSimpleName());     //输出item class : SQLiteCursor   //由于上面第三条日志信息输出的类型为SQLiteCursor,所以采用Cursor的方式获取数据。     Cursor cursor = (Cursor) ((ListView) parent).getItemAtPosition(position);     if (cursor != null && cursor.moveToPosition(position)) {     //做其他操作     }  }  });

四、总结

  目前还是要重点使用positon为上策,更复合程序员的编程习惯(下标以0开始);而id存在一定的变数,也许还未领会其实际用途吧,并且不太理解为什么id要是long类型的。
  onItemClickListener()中的position和id就是这样实现的,那与之相类似的监听器也是如此。毕竟监听器是实际开发中经常用到的,所以弄懂细枝末节还是有必要的。

Android 分析监听器上的参数position和id(一)

 


 

 

你可能感兴趣的:(移动开发,Android开发,监听器,position和id)