承襲上一篇【使用ListView(1)】,現在我們需要定義當按下ListView中的Item後的事件行為:
Item按下去後以Toast顯示物品名稱
- 建立 ItemClick
此Class負責當Item按下去後需產生的行為,extend OnItemClickListener
public class ItemClick implements OnItemClickListener { private Context _context; private List< mydatainfo > _infoList; @SuppressWarnings("unused") private ItemClick(){ } public ItemClick(Context context,List< mydatainfo > list){ _context = context; _infoList = list; } @Override public void onItemClick(AdapterView arg0, View arg1, int position, long arg3) { String text = _infoList.get(position).getName(); Toast.makeText(_context, "按下"+text, Toast.LENGTH_SHORT).show(); } }
- 將 ItemClick 設定至 ListView
我們使用上一篇文章的Code,加入此行(將原先的code反註解即可):
listview.setOnItemClickListener(new ItemClick(this, _datas));
原先的onCreate()變更為如下:
@Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_list_view); _datas = new ArrayList< mydatainfo >(); _listviewDataAdapter = new MyDataAdapter(this,_datas); addNewData(R.drawable.mycard_50_app,"MyCard點數50",50); addNewData(R.drawable.mycard_100_app,"MyCard點數100",100); ListView listview = (ListView) findViewById(R.id.listView1); listview.setAdapter(_listviewDataAdapter); listview.setOnItemClickListener(new ItemClick(this, _datas)); } private void addNewData(int resourceid,String name,int price){ Drawable icon = getResources().getDrawable(resourceid); _datas.add(new MyDataInfo(name,price,icon)); }
沒有留言:
張貼留言