ListActivity 学习[原创]

1. public class ListActivity extends Activity;


2. ListActivity 中包含下面2个重要的字段:

  protected ListAdapter mAdapter;   -- 适配器

  protected ListView mList;      -- ListView


3. 常用方法

  1) protected void onListItemClick(ListView l, View v, int position, long id)

  This method will be called when an item in the list is selected. Subclasses should override. Subclasses can call getListView().getItemAtPosition(position) if they need to access the data associated with the selected item.

  当选择(点击) ListView 中的某个条目时触发该方法. 在子类中必须重写该方法. 在子类中可以通过调用 getListView().getItemAtPosition(position) 方法获取所选择(单击) 的 item 所关联的数据.


  2) public void onContentChanged()

   Updates the screen state (current list and other views) when the content changes.

  当内容发生改变时, 调用此方法, 可以更新屏幕状态(当前 list 和 其他 views).


  3) public void setListAdapter(ListAdapter adapter)

  Provide the cursor for the list view.

  为 list 指定 adapter.


  4) public ListView getListView()

  Get the activity's list view widget.

  获取 activity 的 list view 对象.


  5) public ListAdapter getListAdapter()

  Get the ListAdapter associated with this activity's ListView.

  获取与该 activity 的 ListView 相关联的 Adapter


  记忆: 大部分方法中都包含有 List .


/**
* 设置长按事件
*/
getListView().setOnItemLongClickListener(new OnItemLongClickListener() {
  @Override
  public boolean onItemLongClick(AdapterView<?> parent, View view, int position, long id) {
    Toast.makeText(getApplicationContext(), "Item in position " + position + " clicked", Toast.LENGTH_LONG).show();
    // Return true to consume the click event. 返回 true 的目的在于消耗长按事件
    return true;
    }
});
/**
 * 监听 ListView 中的 item 的单击事件(即,当 ListView中的某个item被单击时,将触发该方法)
 * getItem(position)方法用于获取与item相关联的数据
 * getItemAtPosition(position)在内部也是调用getItem(position)方法
 */
@Override
protected void onListItemClick(ListView l, View v, int position, long id) {
  // Get the item that was clicked
  Object obj = this.getListAdapter().getItem(position);
  HashMap<String, Object> item = (HashMap<String, Object>) obj;

  // 上面两句等同于这一句的调用
  // HashMap<String, Object> item = (HashMap<String, Object>) l.getItemAtPosition(position);
  int iId = (Integer) item.get("id");
  String name = (String) item.get("name");
  System.out.println("iId = " + iId + " :: position = " + position + " :: name = " + name);
}




原文地址:https://www.cnblogs.com/xpxpxp2046/p/2303176.html