android listview的建立及行刪除操作

來源:互聯網
上載者:User

 

Step1:建立listview

 

 

 ListView list = (ListView) findViewById(R.id.ListView01);

  list.setBackgroundColor(Color.WHITE);//設定背景顏色

   list.setCacheColorHint(Color.WHITE);

 

        //產生動態數組,加入資料

        listItem = new ArrayList<HashMap<String, Object>>();

        map = new HashMap<String, Object>();

        for(int i=0;i<10;i++)

        {

         HashMap<String, Object>   map = new HashMap<String, Object>();

               map.put("ItemImage", R.drawable.checked);//映像資源的ID 把表徵圖放到工程的相應木來下

          map.put("ItemTitle", "Level ");

         map.put("ItemText", "Finished in 1 Min 54 Secs, 70 Moves!");

                listItem.add(map);

        }

        //產生適配器的Item和動態數組對應的元素

        SimpleAdapter listItemAdapter = new SimpleAdapter(this,listItem,//資料來源 

            R.layout.list_items,//ListItem的XML實現

            //動態數組與ImageItem對應的子項        

            new String[] {"ItemImage","ItemTitle", "ItemText"}, 

            //ImageItem的XML檔案裡面的一個ImageView,兩個TextView ID

            new int[] {R.id.ItemImage,R.id.ItemTitle,R.id.ItemText}

        );

        //添加並且顯示

        list.setAdapter(listItemAdapter);

 

        //添加點擊

        list.setOnItemClickListener(new OnItemClickListener()

      {

 

@Override

public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,long arg3) 

{

String item = (String)listItem.get(arg2).get("ItemTitle");

setTitle("點擊第"+item);

}

});

 

      //添加長按點擊

        list.setOnCreateContextMenuListener(new OnCreateContextMenuListener()

{

@Override

public void onCreateContextMenu(ContextMenu menu, View v,ContextMenuInfo menuInfo)

{

menu.setHeaderTitle("長按菜單-ContextMenu");   

menu.add(0, 0, 0, "刪除審批單");

menu.add(0, 1, 0, "取消刪除");   

}

}); 

//長按菜單響應函數

@Override

public boolean onContextItemSelected(MenuItem item)

{

setTitle("點擊了長按菜單裡面的第"+item.getItemId()+"個項目"); 

int selectedPosition = ((AdapterContextMenuInfo) item.getMenuInfo()).position;//擷取點擊了第幾行

return super.onContextItemSelected(item);

}

 

刪除操作

listItem.remove(position);//選擇行的位置

listItemAdapter.notifyDataSetChanged();

list.invalidate();

listview會刪除選擇的行,重新更新

 

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.