Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲

Android ListView 添加 HeadView 及點擊事件注意事項

編輯:關於 Android 程式設計

ListView 添加 HeadView 後的點擊事件處理

1. 為頭部 View 設置點擊事件:可用來屏蔽 ListView item 的點擊事件。

 View headerView = getLayoutInflater().inflate(R.layout.listhead, null);
 Button btn = (Button) headerView.findViewById(R.id.button1);
 btn.setOnClickListener(new OnClickListener() {
    @Override
    public void onClick(View arg0) {
        Toast.makeText(MainActivity.this, "bn", Toast.LENGTH_SHORT).show();
    }
});

2. 添加頭部 View:必須放在 setAdapter 之前,否則會報錯。

 lv.addHeaderView(headerView);

3. 準備假數據並設置適配器:注意,若不設置適配器,headView 也不會顯示。

 List> list = new ArrayList>();
 HashMap map = new HashMap();
 map.put("tv", "tv");
 for (int i = 0; i < 6; i++) {
    list.add(map);
 }
 SimpleAdapter sa = new SimpleAdapter(this, list, R.layout.item_lv,
    new String[] { "tv" }, new int[] { R.id.tv });
 lv.setAdapter(sa);

4. 設置 item 點擊事件:關鍵在於 position 與 id 的取值——有 headView 時,position=0 的第一項就是 headView;而 headView 或 footView 的 id 為 -1。

 lv.setOnItemClickListener(new OnItemClickListener() {
    @Override
    public void onItemClick(AdapterView arg0, View arg1, int position, long id) {
        // 有 headView 時 position=0 為 headView
        Toast.makeText(MainActivity.this, "position: " + position, Toast.LENGTH_SHORT).show();
        // 有 headView 或 footView 時,這兩個 view 的 id 為 -1
        if (id == -1) {
            Toast.makeText(MainActivity.this, "head: " + id, Toast.LENGTH_SHORT).show();
        } else {
            Toast.makeText(MainActivity.this, "id: " + id, Toast.LENGTH_SHORT).show();
        }
    }
});

完整流程可歸納為:先 inflate 頭部佈局並綁定其內部控件點擊事件 → addHeaderView(務必在 setAdapter 之前)→ 準備數據與 SimpleAdapter → setAdapter → 設置 item 點擊事件。切記 addHeaderView 與 setAdapter 的先後順序,以及點擊時要正確處理 position 與 id 的偏移。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © Android教程網 All Rights Reserved