1. 程式人生 > >為ListView每個Item上面的按鈕新增事件

為ListView每個Item上面的按鈕新增事件

1.先看下效果圖:

      

在這裡僅供測試,我把資料都寫死了,根據需要可以自己進行修改,此外實現ListView上面每個Item上的Button的事件有兩種方法:

1.使用final變數擴充套件區域性變數的生命週期範圍主要程式碼(本文最後附全部程式碼):

  1. //注意原本getView方法中的int position變數是非final的,現在改為final
  2.         @Override
  3.         public View getView(finalint position, View convertView, ViewGroup parent) {  
  4.              ViewHolder holder = null
    ;  
  5.             if (convertView == null) {  
  6.                 holder=new ViewHolder();    
  7.                 //可以理解為從vlist獲取view  之後把view返回給ListView
  8.                 convertView = mInflater.inflate(R.layout.vlist, null);  
  9.                 holder.title = (TextView)convertView.findViewById(R.id.title);  
  10.                 holder.info = (TextView)convertView.findViewById(R.id.info);  
  11.                 holder.viewBtn = (Button)convertView.findViewById(R.id.view_btn);  
  12.                 convertView.setTag(holder);               
  13.             }else {               
  14.                 holder = (ViewHolder)convertView.getTag();  
  15.             }         
  16.             holder.title.setText((String)mData.get(position).get("title"
    ));  
  17.             holder.info.setText((String)mData.get(position).get("info"));  
  18.             holder.viewBtn.setTag(position);  
  19.             //給Button新增單擊事件  新增Button之後ListView將失去焦點  需要的直接把Button的焦點去掉
  20.             holder.viewBtn.setOnClickListener(new View.OnClickListener() {  
  21.                 @Override
  22.                 publicvoid onClick(View v) {  
  23.                     showInfo(position);                   
  24.                 }  
  25.             });  
  26.             //holder.viewBtn.setOnClickListener(MyListener(position));
  27.             return convertView;  
  28.         }  
  29.     }  
  30.     //提取出來方便點
  31.     publicfinalclass ViewHolder {  
  32.         public TextView title;  
  33.         public TextView info;  
  34.         public Button viewBtn;  
  35.     }  
  36.     publicvoid showInfo(int position){  
  37.         ImageView img=new ImageView(ListViewActivity.this);  
  38.         img.setImageResource(R.drawable.b);  
  39.         new AlertDialog.Builder(this).setView(img)  
  40.         .setTitle("詳情"+position)  
  41.         .setMessage("菜名:"+title[position]+"   價格:"+info[position])  
  42.         .setPositiveButton("確定"new DialogInterface.OnClickListener() {  
  43.             @Override
  44.             publicvoid onClick(DialogInterface dialog, int which) {  
  45.             }  
  46.         })  
  47.         .show();  
  48.     }  


2.使用類記錄每個Button的位置,使每個BUTTON都有自己的Listener主要程式碼:


  1. //****************************************第二種方法,高手一般都用此種方法,具體原因,我還不清楚,有待研究
  2.         public View getView(int position, View convertView, ViewGroup parent) {  
  3.              ViewHolder holder = null;  
  4.              MyListener myListener=null;  
  5.             if (convertView == null) {  
  6.                 holder=new ViewHolder();    
  7.                 //可以理解為從vlist獲取view  之後把view返回給ListView
  8.                  myListener=new MyListener(position);  
  9.                 convertView = mInflater.inflate(R.layout.vlist, null);  
  10.                 holder.title = (TextView)convertView.findViewById(R.id.title);  
  11.                 holder.info = (TextView)convertView.findViewById(R.id.info);  
  12.                 holder.viewBtn = (Button)convertView.findViewById(R.id.view_btn);  
  13.                 convertView.setTag(holder);               
  14.             }else {               
  15.                 holder = (ViewHolder)convertView.getTag();  
  16.             }         
  17.             holder.title.setText((String)mData.get(position).get("title"));  
  18.             holder.info.setText((String)mData.get(position).get("info"));  
  19.             holder.viewBtn.setTag(position);  
  20.             //給Button新增單擊事件  新增Button之後ListView將失去焦點  需要的直接把Button的焦點去掉
  21.             holder.viewBtn.setOnClickListener( myListener);  
  22.             //holder.viewBtn.setOnClickListener(MyListener(position));
  23.             return convertView;  
  24.         }  
  25.     }  
  26.      privateclass MyListener implements OnClickListener{  
  27.             int mPosition;  
  28.             public MyListener(int inPosition){  
  29.                 mPosition= inPosition;  
  30.             }  
  31.             @Override
  32.             publicvoid onClick(View v) {  
  33.                 // TODO Auto-generated method stub
  34.                 Toast.makeText(ListViewActivity.this, title[mPosition], Toast.LENGTH_SHORT).show();  
  35.             }  
  36.         }  
  37.     //提取出來方便點
  38.     publicfinalclass ViewHolder {  
  39.         public TextView title;  
  40.         public TextView info;  
  41.         public Button viewBtn;  
  42.     }  


3.全部程式碼

1.ListViewActivity.java全部程式碼:

  1. package ms.ListView;  
  2. import java.util.ArrayList;  
  3. import java.util.HashMap;  
  4. import java.util.List;  
  5. import java.util.Map;  
  6. import android.app.Activity;  
  7. import android.app.AlertDialog;  
  8. import android.content.Context;  
  9. import android.content.DialogInterface;  
  10. import android.os.Bundle;  
  11. import android.view.LayoutInflater;  
  12. import android.view.View;  
  13. import android.view.View.OnClickListener;  
  14. import android.view.ViewGroup;  
  15. import android.widget.AdapterView;  
  16. import android.widget.AdapterView.OnItemSelectedListener;  
  17. import android.widget.BaseAdapter;  
  18. import android.widget.Button;  
  19. import android.widget.ImageView;  
  20. import android.widget.ListView;  
  21. import android.widget.TextView;  
  22. import android.widget.Toast;  
  23. publicclass ListViewActivity extends Activity {  
  24.     /** Called when the activity is first created. */
  25.     private List<Map<String, Object>> mData;  
  26.     privateint flag;  
  27.     publicstatic String title[]=new String[]{"菜名0","菜名1","菜名2","菜名3","菜名4","菜名5","菜名6","菜名7","菜名8","菜名9"};  
  28.     publicstatic String info[]=new String[]{ "¥:28","¥:28","¥:28","¥:28","¥:28","¥:28","¥:28","¥:28","¥:28","¥:28",};  
  29.     @Override
  30.     publicvoid onCreate(Bundle savedInstanceState) {  
  31.         super.onCreate(savedInstanceState);  
  32.         setContentView(R.layout.main);  
  33.         mData = getData();  
  34.         ListView listView = (ListView) findViewById(R.id.listView);  
  35.         MyAdapter adapter = new MyAdapter(this);  
  36.         listView.setAdapter(adapter);  
  37.     }  
  38.     //獲取動態陣列資料  可以由其他地方傳來(json等)
  39.     private List<Map<String, Object>> getData() {  
  40.         List<Map<String, Object>> list = new ArrayList<Map<String, Object>>();  
  41. for(int i=0;i<title.length;i++){  
  42.         Map<String, Object> map = new HashMap<String, Object>();  
  43.         map.put("title", title[i]);  
  44.         map.put("info", info[i]);  
  45.         list.add(map);  
  46. }  
  47.         return list;  
  48.     }  
  49.     publicclass MyAdapter extends BaseAdapter {  
  50.         private LayoutInflater mInflater;  
  51.         public MyAdapter(Context context) {  
  52.             this.mInflater = LayoutInflater.from(context);  
  53.         }  
  54.         @Override
  55.         publicint getCount() {  
  56.             // TODO Auto-generated method stub
  57.             return mData.size();  
  58.         }  
  59.         @Override
  60.         public Object getItem(int position) {  
  61.             // TODO Auto-generated method stub
  62.             returnnull;  
  63.         }  
  64.         @Override
  65.         publiclong getItemId(int position) {  
  66.             // TODO Auto-generated method stub
  67.             return0;  
  68.         }  
  69.         //****************************************final方法
  70. //注意原本getView方法中的int position變數是非final的,現在改為final
  71.         @Override
  72.         public View getView(finalint position, View convertView, ViewGroup parent) {  
  73.              ViewHolder holder = null;  
  74.             if (convertView == null) {  
  75.                 holder=new ViewHolder();    
  76.                 //可以理解為從vlist獲取view  之後把view返回給ListView
  77.                 convertView = mInflater.inflate(R.layout.vlist, null);  
  78.                 holder.title = (TextView)convertView.findViewById(R.id.title);  
  79.                 holder.info = (TextView)convertView.findViewById(R.id.info);  
  80.                 holder.viewBtn = (Button)convertView.findViewById(R.id.view_btn);  
  81.                 convertView.setTag(holder);               
  82.             }else {               
  83.                 holder = (ViewHolder)convertView.getTag();  
  84.             }         
  85.             holder.title.setText((String)mData.get(position).get("title"));  
  86.             holder.info.setText((String)mData.get(position).get("info"));  
  87.             holder.viewBtn.setTag(position);  
  88.             //給Button新增單擊事件  新增Button之後ListView將失去焦點  需要的直接把Button的焦點去掉
  89.             holder.viewBtn.setOnClickListener(new View.OnClickListener() {  
  90.                 @Override
  91.                 publicvoid onClick(View v) {  
  92.                     showInfo(position);                   
  93.                 }  
  94.             });  
  95.             //holder.viewBtn.setOnClickListener(MyListener(position));
  96.             return convertView;  
  97.         }  
  98.     }  
  99.         //****************************************第二種方法,高手一般都用此種方法,具體原因,我還不清楚,有待研究
  100. //      public View getView(int position, View convertView, ViewGroup parent) {
  101. //           ViewHolder holder = null;
  102. //           MyListener myListener=null;
  103. //          if (convertView == null) {
  104. //              
  105. //              holder=new ViewHolder();  
  106. //              
  107. //              //可以理解為從vlist獲取view  之後把view返回給ListView
  108. //               myListener=new MyListener(position);
  109. //                 
  110. //              convertView = mInflater.inflate(R.layout.vlist, null);
  111. //              holder.title = (TextView)convertView.findViewById(R.id.title);
  112. //              holder.info = (TextView)convertView.findViewById(R.id.info);
  113. //              holder.viewBtn = (Button)convertView.findViewById(R.id.view_btn);
  114. //              convertView.setTag(holder);             
  115. //          }else {             
  116. //              holder = (ViewHolder)convertView.getTag();
  117. //          }       
  118. //          
  119. //          holder.title.setText((String)mData.get(position).get("title"));
  120. //          holder.info.setText((String)mData.get(position).get("info"));
  121. //          holder.viewBtn.setTag(position);
  122. //          //給Button新增單擊事件  新增Button之後ListView將失去焦點  需要的直接把Button的焦點去掉
  123. //          holder.viewBtn.setOnClickListener( myListener);
  124. //          
  125. //          //holder.viewBtn.setOnClickListener(MyListener(position));
  126. //                  
  127. //          return convertView;
  128. //      }
  129. //  }
  130. //  
  131. //   private class MyListener implements OnClickListener{
  132. //          int mPosition;
  133. //          public MyListener(int inPosition){
  134. //              mPosition= inPosition;
  135. //          }
  136. //          @Override
  137. //          public void onClick(View v) {
  138. //              // TODO Auto-generated method stub
  139. //              Toast.makeText(ListViewActivity.this, title[mPosition], Toast.LENGTH_SHORT).show();
  140. //          }
  141. //          
  142. //      }
  143. //
  144. //  
  145.     //提取出來方便點
  146.     publicfinalclass ViewHolder {  
  147.         public TextView title;  
  148.         public TextView info;  
  149.         public Button viewBtn;  
  150.     }  
  151.     publicvoid showInfo(int position){  
  152.         ImageView img=new ImageView(ListViewActivity.this);  
  153.         img.setImageResource(R.drawable.b);  
  154.         new AlertDialog.Builder(this).setView(img)  
  155.         .setTitle("詳情"+position)  
  156.         .setMessage("菜名:"+title[position]+"   價格:"+info[position])  
  157.         .setPositiveButton("確定"new DialogInterface.OnClickListener() {  
  158.             @Override
  159.             publicvoid onClick(DialogInterface dialog, int which) {  
  160.             }  
  161.         })  
  162.         .show();  
  163.     }  
  164. }  

2.main.xml
  1. <?xmlversion="1.0"encoding="utf-8"?>
  2. <LinearLayoutxmlns:android="http://schemas.android.com/apk/res/android"
  3.     android:layout_width="fill_parent"
  4.     android:layout_height="fill_parent"
  5.     android:orientation="vertical">
  6.     <ListView
  7.         android:id="@+id/listView"
  8.         android:layout_width="fill_parent"
  9.         android:layout_height="fill_parent"
  10.         android:divider="@drawable/list_line"
  11.         android:dividerHeight="1dip"/>
  12. </LinearLayout>

3.vlist.xml
  1. <?xmlversion="1.0"encoding="utf-8"?>
  2. <LinearLayoutxmlns:android="http://schemas.android.com/apk/res/android"
  3.     android:layout_width="fill_parent"
  4.     android:layout_height="fill_parent"
  5.     android:orientation="vertical">
  6.     <ListView
  7.         android:id="@+id/listView"
  8.         android:layout_width="fill_parent"
  9.         android:layout_height="fill_parent"
  10.         android:divider="@drawable/list_line"
  11.         android:dividerHeight="1dip"/>
  12. </LinearLayout>

4.btn_detail_selecter.xml
  1. <?xmlversion="1.0"encoding="utf-8"?>
  2. <selectorxmlns:android="http://schemas.android.com/apk/res/android">
  3.     <itemandroid:drawable="@drawable/btn_detail_normal"android:state_enabled="true"android:state_focused="false"android:state_pressed="false"/>
  4.     <itemandroid:drawable="@drawable/btn_detail_pressed"android:state_enabled="true"android:state_pressed="true"/>
  5.     <itemandroid:drawable="@drawable/btn_detail_pressed"android:state_enabled="true"android:state_focused="true"/>
  6. </selector>

5.item.xml
  1. <?xmlversion="1.0"encoding="UTF-8"?>
  2. <selectorxmlns:android="http://schemas.android.com/apk/res/android">
  3.     <itemandroid:drawable="@drawable/item_higlight"android:state_focused="true"android:state_pressed="false"/>
  4.     <itemandroid:drawable="@drawable/item_higlight"android:state_focused="false"android:state_pressed="true"/>
  5.     <itemandroid:drawable="@drawable/item_higlight"android:state_selected="true"/>
  6.     <itemandroid:drawable="@drawable/item_higlight"android:state_focused="true"/>
  7.     <itemandroid:drawable="@drawable/item_higlight"/>
  8. </selector>


6.colors.xml

  1. <?xmlversion="1.0"encoding="UTF-8"?>
  2. <resources>
  3.     <colorname="region">#8000ff00</color>
  4.     <colorname="listTitle">#ff23323b</color>
  5.     <colorname="text">#ff848f9b</color>
  6.     <colorname="write">#ffffffff</color>
  7. </resources>

7.values.xml
  1. <?xmlversion="1.0"encoding="utf-8"?>
  2. <resources>
  3.     <stringname="hello">Hello World, ListViewActivity!</string>
  4.     <stringname="app_name">ListView</string>
  5. </resources>

8.drawables.xml
  1. <?xmlversion="1.0"encoding="UTF-8"?>
  2. <resources>
  3.     <itemtype="drawable"name="bg">#80000000</item>
  4.     <itemtype="drawable"name="transparent">#00000000</item>
  5.     <itemtype="drawable"name="lightblue">#ffcfe1ed</item>
  6.     <itemtype="drawable"name="readmenu_btn_bg_f">#30ffffff</item>
  7.     <itemtype="drawable"name="readmenu_btn_bg_p">#50ffffff</item>
  8.     <itemtype="drawable"name="blackMask">#30000000</item>
  9. </resources>