Android ListView 一

来源:互联网 发布:知彼而知己 打不开 编辑:程序博客网 时间:2024/05/01 08:42

Ttorial and example:


/***********分割线*********/

    So now it is the time to populate our listView. As said before we use a SimpleAdapter, a standard adapter present in SDK. Let’s suppose we want to show a list with the solar system planets. SimpleAdapter accepts a java.util.List with element’s type of java.util.Map. In our case we have then

// The data to showList<Map<String, String>> planetsList = new ArrayList<Map<String,String>>(); .....    private void initList() {    // We populate the planets     planetsList.add(createPlanet("planet", "Mercury"));    planetsList.add(createPlanet("planet", "Venus"));    planetsList.add(createPlanet("planet", "Mars"));    planetsList.add(createPlanet("planet", "Jupiter"));    planetsList.add(createPlanet("planet", "Saturn"));    planetsList.add(createPlanet("planet", "Uranus"));    planetsList.add(createPlanet("planet", "Neptune")); } private HashMap<String, String> createPlanet(String key, String name) {    HashMap<String, String> planet = new HashMap<String, String>();    planet.put(key, name);     return planet;
and the SimpleAdapter can be instantiated as:
/ This is a simple adapter that accepts as parameter// Context// Data list// The row layout that is used during the row creation// The keys used to retrieve the data// The View id used to show the data. The key number and the view id must matchsimpleAdpt = new SimpleAdapter(this, planetsList, android.R.layout.simple_list_item_1, new String[] {"planet"}, new int[] {android.R.id.text1});

     where the first parameter is the context reference (our Activity), the second the data we want so show in the list. The 3rd is the layout we want to use for each row in the list. In this case we just used a pre-built layout shipped with android SDK that you can find inside the android sdk directroy and then platforms\android-16\data\res\layout. This is a very simple layout that contains just a TextView with id text1. The 4th parameter is an array of key used to retrieve the data from the Map. Each list element of java.util.List represents a row in the ListView and each element inside the row must have a unique key that is used to retrieve the element content. In our case to make things very simple we just used planet as key. The 5th element is an array of int representing the ids of the View inside the row layout. In our case is just text1 id. Please notice that the keys array length must match the ids array length.

We have almost done. Let’s modify the onCreate method in our Activity like that:

@Override02public void onCreate(Bundle savedInstanceState) {03    super.onCreate(savedInstanceState);04    setContentView(R.layout.activity_main);05 06    initList();07 08    // We get the ListView component from the layout09    ListView lv = (ListView) findViewById(R.id.listView);10 11    // This is a simple adapter that accepts as parameter12    // Context13    // Data list14    // The row layout that is used during the row creation15    // The keys used to retrieve the data16    // The View id used to show the data. The key number and the view id must match17    simpleAdpt = new SimpleAdapter(this, planetsList, android.R.layout.simple_list_item_1, new String[] {"planet"}, new int[] {android.R.id.text1});18 19    lv.setAdapter(simpleAdpt);20}

User interaction

Once we have created our list and populated it with the items we want to interact with the user giving the chance to click one item or maybe show a context menu. To do it we have to register some listener.

If we want to listen when the user clicks on an item we simply have to implement theAdapterView.OnItemClickListener(). So we have:

01// React to user clicks on item
02lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
03 
04     public void onItemClick(AdapterView<?> parentAdapter, View view, int position,
05                             long id) {
06 
07         // We know the View is a TextView so we can cast it
08         TextView clickedView = (TextView) view;
09 
10         Toast.makeText(MainActivity.this"Item with id ["+id+"] - Position ["+position+"] - Planet ["+clickedView.getText()+"]", Toast.LENGTH_SHORT).show();
11 
12     }
13});

When the user clicks on an item we simply show the position and the id of the item clicked using a simple Toast.

What about if we want to create a context menu when a user long click on an item? Well this is very simple because we have to override the onCreateContextMenu method in the Activity class and register the class as listener. First override the method:

01// We want to create a context Menu when the user long click on an item
02  @Override
03  public void onCreateContextMenu(ContextMenu menu, View v,
04          ContextMenuInfo menuInfo) {
05 
06      super.onCreateContextMenu(menu, v, menuInfo);
07      AdapterContextMenuInfo aInfo = (AdapterContextMenuInfo) menuInfo;
08 
09      // We know that each row in the adapter is a Map
10      HashMap map =  (HashMap) simpleAdpt.getItem(aInfo.position);
11 
12      menu.setHeaderTitle("Options for " + map.get("planet"));
13      menu.add(111"Details");
14      menu.add(122"Delete");
15 
16  }

What do we do in this method? Well first we call super to let the SO makes its work. Then we cast the ContextMenuInfo toAdapterContextMenuInfo because we are using a ListView. The AdapterContextMenuInfo has an attribute that olds the item position clicked se we use this information to retrieve the item information. We know we are using an HashMap to represent the row so we cast the result to HashMap. It is the time we create the menu.

First we create the menu header using the name of the planet retrieved using the HashMap and then set two options “Details” and “Delete” with different ids but belonging to the same group we called “1”.

Before running our project we have to modify onCreate method to register our MainClass as the handler for the context menu for the ListView.

1// we register for the contextmneu       
2registerForContextMenu(lv);

Let’s run our project and when we long click on an item we will get:

The last step is handle when user clicks on one of the options. We have to override the method onContextItemSelectedlike that:

1// This method is called when user selects an Item in the Context menu
2@Override
3public boolean onContextItemSelected(MenuItem item) {
4    int itemId = item.getItemId();
5    // Implements our logic
6    Toast.makeText(this"Item id ["+itemId+"]", Toast.LENGTH_SHORT).show();
7    return true;
8}

In this case we simply show a Toast with the menu item id.
 

Reference: Android ListView – Tutorial and basic example from our JCG partner Francesco Azzola at the Surviving w/ Android blog.



0 0
原创粉丝点击