首页 > 代码库 > android开发中 listview和checkbox结合

android开发中 listview和checkbox结合

通过重写listview的adapter,将listview和checkbox结合在一起,并且二者可以分别操作。

[1].[文件] activity_menu.xml ~ 2KB   下载(13)跳至 [1] [2] [3] [4]

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
<LinearLayoutxmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="vertical"
>
     <ListView
        android:id="@+id/android:list"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_weight="2.0"
        android:scrollbars="vertical"/>
    <TextView
        android:id="@+id/foodname"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_weight="1.0"
        android:textSize="20dp"
        android:text=""/>
      <TextView
        android:id="@+id/price"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_weight="1.0"
        android:textSize="20dp"
        android:text=""/>
    <LinearLayout
        android:layout_width="fill_parent"
        android:layout_height="wrap_content">
        <Button
            android:id="@+id/call"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:background="@drawable/thphone1"
            android:layout_weight="1.0"
        android:textSize="20dp"
            android:text="电话订餐"/>
         <Button
        android:id="@+id/cancelButton"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_weight="1.0"
        android:textSize="20dp"
        android:text="取消"/>
        
    </LinearLayout>
     
</LinearLayout>

[2].[文件] listview_style.xml ~ 1KB   下载(7)跳至 [1] [2] [3] [4]

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
<?xmlversion="1.0"encoding="utf-8"?>
<RelativeLayoutxmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/RelativeLayout01"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:paddingBottom="4dip"
    android:paddingLeft="12dip"
    android:paddingRight="12dip">
<CheckBox
        android:id="@+id/CheckBox01"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentRight="true"
        android:focusable="false"
         android:clickable="false"
        android:focusableInTouchMode="false"
        android:gravity="center_vertical"
        android:paddingTop="12dip"
        >
    </CheckBox>
    <TextView
        android:id="@+id/topTextView"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:text="TextView1"
        android:textSize="20dip"/>
    <TextView
        android:id="@+id/bottomTextView"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_below="@+id/topTextView"
        android:text="TextView2">
    </TextView>
</RelativeLayout>

[3].[文件] MenuActivity.java ~ 6KB   下载(7)跳至 [1] [2] [3] [4]

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
package com.amaker.wlo;
importjava.io.InputStream; importjava.net.URL; importjava.net.URLConnection; importjava.util.ArrayList; importjava.util.HashMap; importjava.util.List;
importjavax.xml.parsers.DocumentBuilder; importjavax.xml.parsers.DocumentBuilderFactory;
importorg.w3c.dom.Document; importorg.w3c.dom.NodeList;
importandroid.app.Activity; importandroid.content.Context; importandroid.content.Intent; importandroid.content.SharedPreferences; importandroid.content.pm.PackageManager.NameNotFoundException;import android.net.Uri;import android.os.Bundle;import android.view.View;import android.view.View.OnClickListener;import android.widget.AdapterView;import android.widget.AdapterView.OnItemClickListener;import android.widget.Button;import android.widget.ListView;import android.widget.RelativeLayout;import android.widget.TextView;
importcom.amaker.util.HttpUtil;
publicclass MenuActivity extends Activity {
    privateListView listview;
    privateTextView totalPrice;
    privateTextView totalFood;
    privateButton callBtn;
    privateButton cancleBtn;
    @Override
    protectedvoid onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_menu);
        
        listview=(ListView)findViewById(android.R.id.list);
        
         totalPrice=(TextView)findViewById(R.id.price);
         
         totalFood=(TextView)findViewById(R.id.foodname);
         
         callBtn=(Button)findViewById(R.id.call);
         callBtn.setOnClickListener(callListener);
         
         cancleBtn=(Button)findViewById(R.id.cancelButton);
         cancleBtn.setOnClickListener(canclelistener);
         
         Context context=null;
            try {
                context= createPackageContext("com.amaker.wlo", Context.CONTEXT_IGNORE_SECURITY);
            } catch (NameNotFoundException e) {
               // TODO Auto-generated catch block                e.printStackTrace();
            }
            SharedPreferences preferences = context.getSharedPreferences("shop_id", MODE_WORLD_WRITEABLE);
            int shopid=preferences.getInt("shopid",0);
            
          
         
        String urlStr = HttpUtil.BASE_URL + "servlet/FoodServlet?shopId="+shopid;
        try {
            // 实例化URL             URL url = new URL(urlStr);
            // URLConnection 实例             URLConnection conn = url.openConnection();
            // 获得输入流             InputStream in = conn.getInputStream();
            // 获得DocumentBuilderFactory对象             DocumentBuilderFactory factory = DocumentBuilderFactory
                   .newInstance();
            // 获得DocumentBuilder对象             DocumentBuilder builder = factory.newDocumentBuilder();
            // 获得Document对象             Document doc = builder.parse(in);
            // 获得节点列表             NodeList nl = doc.getElementsByTagName("food");
            // Spinner数据             ArrayList<HashMap<String, Object>> listitem = newArrayList<HashMap<String, Object>>();
            // 获得XML数据             for (inti = 0; i < nl.getLength(); i++) {
               // 商家編號                 // 商家名字foodPrice                 String foodName = doc.getElementsByTagName("foodName")
                       .item(i).getFirstChild().getNodeValue();
               String foodPrice = doc.getElementsByTagName("foodPrice")
                       .item(i).getFirstChild().getNodeValue();
               HashMap<String, Object> map = newHashMap<String, Object>();
               map.put("foodName", foodName);
               map.put("foodPrice", foodPrice+"元");
               listitem.add(map);
            }
            MenuListAdapter listAdapter = newMenuListAdapter(this,listitem, R.layout.listview_style,
                   new String[] { "foodName", "foodPrice"}, 
                   new int[] { R.id.topTextView, R.id.bottomTextView }
            );
            
            listview.setAdapter(listAdapter);
            listview.setOnItemClickListener(getMenu);
        }catch (Exception e) {
            e.printStackTrace();
        }
        
        
    }
    
    OnItemClickListener getMenu=newOnItemClickListener() {
        
        int sumprice=0//定义一个存储所有价格的变量         String sumfood=""//定义一个存储所有食物的变量         @Override
        public void onItemClick(AdapterView<?> parent, View view, intposition,
               long id) {
            
               RelativeLayout lr = (RelativeLayout) view;
               
              
            
               
               
               
               TextView tvtop = (TextView) lr.getChildAt(1);
                
               String foodName=tvtop.getText().toString()+" ";
                
                
                
                
               TextView tv = (TextView) lr.getChildAt(2);
               
               String s = tv.getText().toString();
               
              int foodprice=Integer.parseInt(s.substring(0, s.indexOf("元")));
               
               
              
              
             // 取得ViewHolder对象,这样就省去了通过层层的findViewById去实例化我们需要的cb实例的步骤               ViewHolder holder = (ViewHolder) view.getTag();
               // 改变CheckBox的状态                 holder.cb.toggle();
               // 将CheckBox的选中状况记录下来                 MenuListAdapter.getIsSelected().put(position, holder.cb.isChecked()); 
               // 调整选定条目                 if (holder.cb.isChecked() == true) {
                   sumprice=sumprice+foodprice;
                   sumfood=sumfood+foodName;
               } else {
                   sumprice=sumprice-foodprice;
                   sumfood=sumfood.replace(foodName, "");
                    
               }
               // 用TextView显示                 totalPrice.setText("你預計消費:  "+sumprice);
                   
                   
               totalFood.setText("你已經點了:  "+sumfood);
                
               
            
        }
    };
         
          
        OnClickListener callListener=newOnClickListener() {
        
        @Override
        public void onClick(View v) {
            Context context=null;
            try {
                context= createPackageContext("com.amaker.wlo", Context.CONTEXT_IGNORE_SECURITY);
            } catch (NameNotFoundException e) {
               // TODO Auto-generated catch block                e.printStackTrace();
            }
            SharedPreferences pref = context.getSharedPreferences("phoneinfo", MODE_WORLD_WRITEABLE);
            String PhoneNum=pref.getString("PhoneNum","");
            Intent intent = newIntent(Intent.ACTION_CALL,Uri.parse("tel:"+PhoneNum));  
            startActivity(intent);  
            
        }
    };
               
    OnClickListener canclelistener=newOnClickListener() {
        
        @Override
        public void onClick(View v) {
            Intent intent=newIntent(MenuActivity.this,MainMenuActivity.class);
            startActivity(intent);
            
        }
    };
                
        
}

[4].[文件] MenuListAdapter.java ~ 2KB   下载(7)跳至 [1] [2] [3] [4]

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
package com.amaker.wlo;
importjava.util.ArrayList; importjava.util.HashMap; importjava.util.List; importjava.util.Map;
importandroid.content.Context; importandroid.view.LayoutInflater; importandroid.view.View; importandroid.view.ViewGroup; importandroid.widget.BaseAdapter; importandroid.widget.CheckBox; importandroid.widget.SimpleAdapter; importandroid.widget.TextView;
publicclass MenuListAdapter extends SimpleAdapter {
    // 用来控制CheckBox的选中状况    private staticHashMap<Integer, Boolean> isSelected;
    // 用来导入布局    private LayoutInflater inflater =null;
    privateList<? extends Map<String, ?>> Mdata;
    publicMenuListAdapter(Context context,
            List<? extends Map<String, ?>> data, int resource, String[] from,
            int[] to) {
        super(context, data, resource, from, to);
        this.Mdata=http://www.mamicode.com/data;
        isSelected=new HashMap<Integer, Boolean>();
        inflater = LayoutInflater.from(context);
        initDate();
    }
    
    privatevoid initDate(){
        for(inti=0; i<Mdata.size();i++) {
            getIsSelected().put(i,false);
        }
    }
    @Override
    publicView getView(intposition, View convertView, ViewGroup parent) {
        ViewHolder holder = null;
        if (convertView == null) {
            // 获得ViewHolder对象             holder = new ViewHolder();
            // 导入布局并赋值给convertview             convertView = inflater.inflate(R.layout.listview_style, null);
            holder.tv1 = (TextView) convertView.findViewById(R.id.topTextView);
            holder.tv2 = (TextView) convertView.findViewById(R.id.bottomTextView);
            holder.cb = (CheckBox) convertView.findViewById(R.id.CheckBox01);
            // 为view设置标签             convertView.setTag(holder);
        } else {
            // 取出holder             holder = (ViewHolder) convertView.getTag();
        }
        // 设置list中TextView的显示         //holder.tv1.setText();         holder.tv1.setText(((Map)getItem(position)).get("foodName").toString());
        holder.tv2.setText(((Map)getItem(position)).get("foodPrice").toString());
        // 根据isSelected来设置checkbox的选中状况         holder.cb.setChecked(getIsSelected().get(position));
        return convertView;
    }
    publicstatic HashMap<Integer, Boolean> getIsSelected() {
        return isSelected;
    }
    publicstatic void setIsSelected(HashMap<Integer, Boolean> isSelected) {
        MenuListAdapter.isSelected = isSelected;
    }
}
classViewHolder {
    TextView tv1;
    TextView tv2;
    CheckBox cb;
}

android开发中 listview和checkbox结合