Android中ExpandableListView + BaseAdapter使用详解

Android中ListView的用法基本上学的时候都会使用,其中可以使用ArrayAdapter,SimpleAdapter,BaseAdapter去实现,这次主要使用的 ExpandableListView展示一种两层的效果,ExpandableListView是android中可以实现下拉list的一个控件类似于QQ那种我好友之后就是一排自己的好友,就是两层效果,实现的话使用SimpleExpandableListAdapter即可。

本文只提供参考,如有疑问先发博文支持一下本博客,呵呵,在联系:346933996;原创地址:http://www.kwstu.com/ArticleView/android_201411190928008874

先看看效果:

  

页面布局代码:
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
<?xml version="1.0" encoding="utf-8"?>
     <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
         android:layout_width="fill_parent"
         android:layout_height="fill_parent"
         android:orientation="vertical"
    android:background="#f6f6f6">
    <RelativeLayout
        android:layout_width="fill_parent"
        android:layout_height="fill_parent">
        <LinearLayout
            android:orientation="vertical"
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:layout_alignParentTop="true">
            <include
                android:id="@+id/titleIndex"
                layout="@layout/title_main" />
            <LinearLayout
                android:orientation="horizontal"
                android:layout_width="fill_parent"
                android:layout_height="wrap_content"
                android:background="#e9e9e9"
                android:padding="10dp">
                <LinearLayout
                    android:orientation="horizontal"
                    android:layout_width="fill_parent"
                    android:layout_height="wrap_content">
                    <EditText
                        android:layout_width="wrap_content"
                        android:layout_height="wrap_content"
                        android:id="@+id/keywordstxt"
                        android:background="@drawable/search_txt"
                        android:paddingLeft="10dp" />
                    <ImageButton
                        android:layout_width="wrap_content"
                        android:layout_height="wrap_content"
                        android:id="@+id/searchbtn"
                        android:background="@drawable/search_btn" />
                </LinearLayout>
            </LinearLayout>
            <LinearLayout
                android:orientation="horizontal"
                android:layout_width="fill_parent"
                android:layout_height="wrap_content"
                android:paddingLeft="10dp"
                android:paddingRight="10dp"
                android:layout_marginTop="2dp"
                android:layout_marginBottom="75dp">
                <ExpandableListView
                         android:id="@+id/list"
                         android:layout_width="fill_parent"
                         android:layout_height="fill_parent"
                         android:background="@drawable/view_yuan_morelist"
                         android:cacheColorHint="#00000000"
                         android:listSelector="#00000000"
                         android:groupIndicator="@null"
                         android:childDivider="#d5d5d5"
                         android:dividerHeight="1dp"
                         android:divider="#d5d5d5"/>
            </LinearLayout>
        </LinearLayout>
        <LinearLayout
            android:orientation="vertical"
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:layout_alignParentBottom="true">
            <LinearLayout
                android:orientation="horizontal"
                android:layout_width="fill_parent"
                android:layout_height="wrap_content">
                <ImageView
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:id="@+id/adiv"
                    android:background="@drawable/ad" />
            </LinearLayout>
        </LinearLayout>
    </RelativeLayout>
</LinearLayout>

 

Activity代码:

 

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
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
package coalsms.kwstu.coalsms;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.widget.EditText;
import android.widget.ExpandableListView;
import android.widget.ExpandableListView.OnChildClickListener;
import android.widget.ImageView;
import android.widget.Toast;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.List;
import Adapter.expandableListAdapter;
import Json.JsonTools;
import http.HttpUtils;
import models.DateList;
import models.SmsBase;
/**
 
 * Created by Administrator on 2014/10/26.
 
 */
public class MainActivity extends Activity  {
    ExpandableListView expandableListView=null;
    private expandableListAdapter adapter;
    private List<DateList> listGroup=null;
    private List<SmsBase> listked=null;
    EditText keywordstxt=null;
    private ProgressDialog progressDialoggroup;
    private ProgressDialog progressDialogked;
    private ImageView ad=null;
    @Override
    protected void onPause() {
        adapter.notifyDataSetChanged();
        super.onPause();
    }
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        expandableListView = (ExpandableListView) findViewById(R.id.list);
        progress();
        //加载广告信息
        ad = (ImageView) findViewById(R.id.adiv);
        //图片资源
        String url = "http://hayi.kwstu.com/Content/Images/Ad/ad.png";
        //得到可用的图片
        Bitmap bitmap = getHttpBitmap(url);
        //显示
        ad.setImageBitmap(bitmap);
         //搜索
        keywordstxt  = (EditText) findViewById(R.id.keywordstxt);
        ImageView searchBtn = (ImageView) findViewById(R.id.searchbtn);
        searchBtn.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {
                Intent intent = new Intent();
                intent.setClass(MainActivity.this, SearchReasultActivity.class);
                Bundle bundle = new Bundle();
                bundle.putString("keywordTxt",keywordstxt.getText().toString().trim());
                intent.putExtras(bundle);
                startActivity(intent);
            }
        });
        //设置
        ImageView setup = (ImageView) findViewById(R.id.setup);
        setup.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {
                Intent intent = new Intent();
                intent.setClass(MainActivity.this, SetupActivity.class);
                startActivity(intent);// 启动Activity
                finish();
            }
        });
        //设置item点击的监听器
        expandableListView.setOnChildClickListener(new OnChildClickListener() {
            @Override
            public boolean onChildClick(ExpandableListView parent, View v,
                                        int groupPosition, int childPosition, long id) {
                return false;
            }
        });
        expandableListView.setOnGroupClickListener(new ExpandableListView.OnGroupClickListener() {
            @Override
            public boolean onGroupClick(ExpandableListView parent, View clickedView, int groupPosition, long groupId) {
                adapter.Clear();
                progressKey(listGroup.get(groupPosition).getDATETMP());
                return false;//返回true表示此事件在此被处理了
            }
        });
      //点击某一项关闭其他项
        expandableListView.setOnGroupExpandListener(new ExpandableListView.OnGroupExpandListener() {
            @Override
            public void onGroupExpand(int groupPosition) {
                for (int i = 0; i < listGroup.size(); i++) {
                    if (groupPosition != i) {
                        expandableListView.collapseGroup(i);
                    }
                }
            }
        });
    }
    Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            Bundle data = null;
            data = msg.getData();
            String jsonString = "",jsonStringKed = "";
            switch (msg.what) {
                case 1:
                    progressDialoggroup.cancel();
                    jsonString = (String) data.get("jsonString");
                    listGroup = JsonTools.getDateList(
                            "DateList", jsonString);
                    jsonStringKed = (String) data.get("jsonStringKed");
                    listked = JsonTools.getSmsBaseList(
                            "SmsList", jsonStringKed);
                    adapter= new expandableListAdapter(listGroup,listked,MainActivity.this);
                    expandableListView.setAdapter(adapter);
                    break;
                case 2:
                    progressDialogked.cancel();
                    jsonString = (String) data.get("jsonString");
                    listked = JsonTools.getSmsBaseList(
                            "SmsList", jsonString);
                    if(listked.size()==0)
                    Toast.makeText(
                            MainActivity.this,
                            "暂时无数",Toast.LENGTH_SHORT).show();
                    for (int i = 0; i < listked.size(); i++) {
                        adapter.addItem(listked.get(i));
                    }
                    adapter.notifyDataSetChanged();
                    break;
            }
            super.handleMessage(msg);
        }
    };
    //获取组列表
    public void progress() {
        progressDialoggroup = new ProgressDialog(this);
        progressDialoggroup.setMessage("正在加载......");
        progressDialoggroup.setTitle("消息");
        progressDialoggroup.show();
        beginThread thread = new beginThread();
        thread.start();
    }
    class beginThread extends Thread {
        public void run() {
            handler.sendEmptyMessage(0);
            try {
                String jsonString="",jsonStringKed="";
                jsonString = HttpUtils
                            .getJsonContent(InitActivity.webserviceUrl
                                    + "****/getListDate?username="+****+"&days="+InitActivity.showDays);
                jsonStringKed = HttpUtils
                        .getJsonContent(InitActivity.webserviceUrl
                                + "88888/getListSms?888="+InitActivity.8888+"&curday=2013-01-01");
                Message message = new Message();
                Bundle data = new Bundle();
                data.putString("jsonString", jsonString);
                data.putString("jsonStringKed", jsonStringKed);
                message.what = 1;
                message.setData(data);
                handler.sendMessage(message);
            } catch (Exception e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
    };
 
    //获取子项目列表
    public void progressKey(String dateStr) {
        progressDialogked = new ProgressDialog(this);
        progressDialogked.setMessage("正在加载......");
        progressDialogked.setTitle("消息");
        progressDialogked.show();
        beginKedThread thread = new beginKedThread(dateStr);
        thread.start();
    }
    class beginKedThread extends Thread {
        String dateStr="";
        public beginKedThread(String dateStr){
            this.dateStr=dateStr;
        }
        public void run() {
            handler.sendEmptyMessage(0);
            try {
                String jsonString="";
                jsonString = HttpUtils
                        .getJsonContent(InitActivity.webserviceUrl
                                + "888/8888?username="+InitActivity.888+"&curday="+dateStr);
                Message message = new Message();
                Bundle data = new Bundle();
                data.putString("jsonString", jsonString);
                message.what = 2;
                message.setData(data);
                handler.sendMessage(message);
            } catch (Exception e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
    };
    /**
     * 获取网落图片资源
     * @param url
     * @return
     */
    public static Bitmap getHttpBitmap(String url){
        URL myFileURL;
        Bitmap bitmap=null;
        try{
            myFileURL = new URL(url);
            //获得连接
            HttpURLConnection conn=(HttpURLConnection)myFileURL.openConnection();
            //设置超时时间为6000毫秒,conn.setConnectionTiem(0);表示没有时间限制
            conn.setConnectTimeout(6000);
            //连接设置获得数据流
            conn.setDoInput(true);
            //不使用缓存
            conn.setUseCaches(false);
            //这句可有可无,没有影响
            //conn.connect();
            //得到数据流
            InputStream is = conn.getInputStream();
            //解析得到图片
            bitmap = BitmapFactory.decodeStream(is);
            //关闭数据流
            is.close();
        }catch(Exception e){
            e.printStackTrace();
        }
        return bitmap;
    }
}

 

expandableListAdapter代码

 

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
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
package Adapter;
import android.app.Activity;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.text.Html;
import android.text.method.ArrowKeyMovementMethod;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AbsListView;
import android.widget.BaseExpandableListAdapter;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import java.io.InputStream;
import java.util.HashMap;
import java.util.List;
import coalsms.kwstu.coalsms.InitActivity;
import coalsms.kwstu.coalsms.R;
import models.DateList;
import models.SmsBase;
import models.VersionModel;
/**
 * Created by Administrator on 2014/10/27.
 */
public class expandableListAdapter extends BaseExpandableListAdapter {
    List<DateList> lists = null;
    List<SmsBase> kedList = null;
    Activity activity = null;
    int curItem=0;
    private DBAdapter db = null;
    public expandableListAdapter(List<DateList> list, List<SmsBase> KedList , Activity activity) {//
        super();
        this.lists = list;
        this.kedList = KedList;
        this.activity = activity;
        this.db = new DBAdapter(activity);
    }
    //设置组视图的图片
    int[] logos = new int[]{R.drawable.listlbg};
    //重写ExpandableListAdapter中的各个方法
    @Override
    public int getGroupCount() {
        // TODO Auto-generated method stub
        return lists.size();
    }
    public void addItem(SmsBase item) {
        kedList.add(item);
    }
    public void Clear() {
        // TODO Auto-generated method stub
        this.kedList.clear();
    }
    @Override
    public Object getGroup(int groupPosition) {
        // TODO Auto-generated method stub
        return lists.get(groupPosition);
    }
    @Override
    public long getGroupId(int groupPosition) {
        // TODO Auto-generated method stub
        return groupPosition;
    }
    @Override
    public int getChildrenCount(int groupPosition) {
        // TODO Auto-generated method stub
        return kedList.size();
    }
    @Override
    public Object getChild(int groupPosition, int childPosition) {
        // TODO Auto-generated method stub
        return kedList.get(childPosition);
    }
    @Override
    public long getChildId(int groupPosition, int childPosition) {
        // TODO Auto-generated method stub
        return childPosition;
    }
    @Override
    public boolean hasStableIds() {
        // TODO Auto-generated method stub
        return true;
    }
    @Override
    public View getGroupView(int groupPosition, boolean isExpanded,
                             View convertView, ViewGroup parent) {
        AbsListView.LayoutParams lp = new AbsListView.LayoutParams(
                ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.MATCH_PARENT);
        AbsListView.LayoutParams lpTxt = new AbsListView.LayoutParams(
                ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT);
 
        RelativeLayout.LayoutParams rpl = new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.WRAP_CONTENT, RelativeLayout.LayoutParams.WRAP_CONTENT);
        rpl.addRule(RelativeLayout.ALIGN_PARENT_LEFT, RelativeLayout.TRUE);
 
        RelativeLayout.LayoutParams rpr = new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.WRAP_CONTENT, RelativeLayout.LayoutParams.MATCH_PARENT);
        rpr.addRule(RelativeLayout.ALIGN_PARENT_RIGHT, RelativeLayout.TRUE);
        // TODO Auto-generated method stub
        RelativeLayout rl = new RelativeLayout(
                activity);
        LinearLayout ll = new LinearLayout(
                activity);
        LinearLayout lr = new LinearLayout(
                activity);
        ll.setOrientation(0);
        ll.setLayoutParams(rpl);
        lr.setLayoutParams(rpr);
        lr.setPadding(0, 20, 15, 0);
        ImageView logo = new ImageView(activity);
        logo.setImageResource(logos[0]);
        logo.setPadding(0, 0, 0, 0);
        ll.addView(logo);
        TextView textViewDate = new TextView(
                activity);
        textViewDate.setLayoutParams(lp);
        textViewDate.setGravity(Gravity.CENTER_VERTICAL);
        textViewDate.setPadding(0, 0, 10, 0);
        textViewDate.setTextSize(16);
        textViewDate.setTextColor(Color.rgb(86,86,86));
        textViewDate.setText(lists.get(groupPosition).getDATETMP());
        ll.addView(textViewDate);
        TextView textViewWeek = new TextView(
                activity);
        textViewWeek.setLayoutParams(lp);
        textViewWeek.setGravity(Gravity.CENTER_VERTICAL);
        textViewWeek.setPadding(0, 0, 30, 0);
        textViewWeek.setTextSize(24);
        if(groupPosition==0)
        {
            textViewWeek.setTextColor(Color.rgb(0, 153, 68));
            textViewWeek.setText("今天");
        }
        else {
            textViewWeek.setTextColor(Color.rgb(0, 104, 183));
            textViewWeek.setText(lists.get(groupPosition).getWEEKTMP());
        }
        ll.addView(textViewWeek);
        TextView textViewCount = new TextView(
                activity);
        textViewCount.setLayoutParams(lpTxt);
        textViewCount.setGravity(Gravity.CENTER);
        textViewCount.setPadding(0, 0, 0, 0);
        textViewCount.setTextSize(20);
        textViewCount.setTextColor(Color.WHITE);
        textViewCount.setText(lists.get(groupPosition).getCOUNTTMP());
        textViewCount.setBackgroundResource(R.drawable.count_bg);
        lr.addView(textViewCount);
        rl.addView(ll);
        rl.addView(lr);
        return rl;
    }
    @Override
    public View getChildView(int groupPosition, final int childPosition,
                             boolean isLastChild, View convertView, ViewGroup parent) {
        // TODO Auto-generated method stub
        convertView = LayoutInflater.from(activity).inflate(R.layout.layout_listview_item, null);
        TextView t1 = (TextView)convertView.findViewById(R.id.ItemTitle);
        TextView t2 = (TextView)convertView.findViewById(R.id.ItemText);
        ImageView iv = (ImageView)convertView.findViewById(R.id.scbtn);
        String content=kedList.get(childPosition).getCONTENT();
        iv.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {
                //写入本地数据库
                db.open();
                long id;
                //写入数据
                //判断是否收藏过
                Cursor c = db.getCollectionById(kedList.get(childPosition).getID());
                if(c.getCount()==0) {
                    id = db.insertCollection(kedList.get(childPosition).getID(), kedList.get(childPosition).getCONTENT());
                    Toast toast = Toast.makeText(activity,
                            "收藏成功", Toast.LENGTH_LONG);
                    toast.setGravity(Gravity.CENTER, 0, 0);
                    toast.show();
                }else{
                    Toast toast = Toast.makeText(activity,
                            "此短讯已经收藏,不能重复收藏", Toast.LENGTH_LONG);
                    toast.setGravity(Gravity.CENTER, 0, 0);
                    toast.show();
                }
                db.close();
            }
        });
        t1.setTextSize(InitActivity.fontSize);
        t1.setTextColor(Color.rgb(86, 86, 86));
        t1.setTextIsSelectable(true);
        t1.setText(Html.fromHtml(content));
        t2.setText(Html.fromHtml(kedList.get(childPosition).getSENDTIME()));
        t2.setTextSize(InitActivity.fontSize);
        t2.setTextColor(Color.rgb(204,204,204));
        return convertView;
    }
    final Html.ImageGetter imageGetter = new Html.ImageGetter() {
        public Drawable getDrawable(String source) {
            Drawable d = null;
            try {
                InputStream is = new DefaultHttpClient()
                        .execute(new HttpGet(source)).getEntity()
                        .getContent();
                Bitmap bm = BitmapFactory.decodeStream(is);
                d = new BitmapDrawable(bm);
                d.setBounds(0, 0, bm.getWidth(), bm.getHeight());
            } catch (Exception e) {
                e.printStackTrace();
            }
            return d;
        }
    };
    /*** 半角转换为全角
     *
     * @param input
     * @return
     */
    public static String ToDBC(String input) {
        char[] c = input.toCharArray();
        for (int i = 0; i < c.length; i++) {
            if (c[i] == 12288) {
                c[i] = (char) 32;
                continue;
            }
            if (c[i] > 65280 && c[i] < 65375)
                c[i] = (char) (c[i] - 65248);
        }
        return new String(c);
    }
    @Override
    public boolean isChildSelectable(int groupPosition,
                                     int childPosition) {
        // TODO Auto-generated method stub
        return true;
    }
}

 

posted @ 2016-11-28 19:25  天涯海角路  阅读(227)  评论(0)    收藏  举报