Get Item index in item click event : ListView « UI « Android






Get Item index in item click event

   

package app.test;


import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.AdapterView.OnItemClickListener;

public class Test extends Activity {

  private List<Map<String, Object>> data;
  private ListView listView = null;

  @Override
  public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    PrepareData();
    listView = new ListView(this);

     SimpleAdapter adapter = new SimpleAdapter(this, data,android.R.layout.simple_list_item_1, new String[] { "AAA" },
     new int[] { android.R.id.text1 });
    listView.setAdapter(adapter);
    setContentView(listView);  
    
    OnItemClickListener listener = new OnItemClickListener() {
      public void onItemClick(AdapterView<?> parent, View view, int position,
          long id) {
        setTitle(parent.getItemAtPosition(position).toString());
      }
    };
    listView.setOnItemClickListener(listener);
  }

  private void PrepareData() {
    data = new ArrayList<Map<String, Object>>();
    Map<String, Object> item;
    item = new HashMap<String, Object>();
    item.put("1", "A");
    item.put("2", "B");
    data.add(item);
    item = new HashMap<String, Object>();
    item.put("3", "C");
    item.put("4", "D");
    data.add(item);
    item = new HashMap<String, Object>();
    item.put("5", "E");
    item.put("6", "F");
    data.add(item);
  }
}

   
    
    
  








Related examples in the same category

1.Using ExpandableListView
2.Using ListView
3.Using SimpleAdapter to fill data to ListView
4.Custom cell Renderer for ListView
5.Provide xml layout for ListView Item
6.Fill contact information to ListView
7.ListView.CHOICE_MODE_MULTIPLE
8.Use AbsListView OnScrollListener(AbsListView.OnScrollListener), AbsListView#setOnItemScrollListener(AbsListView.OnItemScrollListener)} to display the first letter of the visible range of cheeses.
9.This demo illustrates the use of CHOICE_MODE_MULTIPLE_MODAL, a.k.a. selection mode on ListView.
10.FileList extends ListView
11.set ListView Height Based On Children
12.Adding a List
13.Lunch List
14.On nothing selected event
15.Create List