ExpandableListview的使用介绍

来源:互联网 发布:建筑学知乎 编辑:程序博客网 时间:2024/06/04 18:08

最近在做一个二级列表,遇到各种问题, 虽然网上有各种资料,但都是写的死数据,不是很详细,特此记录一下,不多说直接上代码:

请求网络:

public class HttpsUtils {private static HttpURLConnection conn;private static URL url;public static String readParser(String urlPath) throws Exception {    ByteArrayOutputStream os = new ByteArrayOutputStream();    byte[] data = new byte[1024];    int len = 0;    url = new URL(urlPath);    conn = (HttpURLConnection) url.openConnection();    conn.setRequestMethod("POST");    conn.setDoInput(true);        //设置输入流采用字节流    conn.setDoOutput(true);        //设置输出流采用字节流    conn.setRequestProperty("Content-type", "text/html");    conn.setRequestProperty("Accept-Charset", "GB2312");    conn.setRequestProperty("contentType", "GB2312");    InputStream is = conn.getInputStream();    while((len= is.read(data)) != -1) {    os.write(data, 0, len);    }    is.close();    return new String(os.toByteArray(),"GB2312");    }}
</pre><pre name="code" class="html">Json解析网络的数据:
</pre><pre name="code" class="html">/*** * 解析数据展示到控件上 * @param urlPath 解析的地址 * @return List */  public static List<PersonItemBean> getdata(String urlPath) {PersonItemBean personItemBean ;//PersonItemBean -> Title ,List<PersonBean>List<PersonItemBean> listTitle = new ArrayList<PersonItemBean>();    try {JSONObject jsonObject = new JSONObject(urlPath);//获取到data数组JSONArray array = jsonObject.getJSONArray("data");//遍历数组for(int i=0;i<array.length();i++) {//存放name的listList<PersonBean> list = new ArrayList<PersonBean>();//存放title List<PersonBean>personItemBean = new PersonItemBean();//获取到data数组下的ObjectJSONObject jsonObject2 = array.getJSONObject(i);//获取到titleString title = jsonObject2.getString("title");//设置titlepersonItemBean.setTitle(title);//获取names节点下的所有数据JSONArray jsonArray = jsonObject2.getJSONArray("names");for(int j=0;j<jsonArray.length();j++) {//获取name的BeanPersonBean bean = new PersonBean();//获取names数组下的ObejctJSONObject object = jsonArray.getJSONObject(j);//获取name名称String childName = object.getString("name");//将获取到name设置到Beanbean.setName(childName);//添加到List集合中list.add(bean);}//将获取到name集合添加到PersonItemBean中personItemBean.setList(list);listTitle.add(personItemBean);}} catch (JSONException e) {e.printStackTrace();}    return listTitle;    }

适配器:

public class ContactFragmentAdapter extends BaseExpandableListAdapter {private List<PersonItemBean> list;private LayoutInflater inflater;public ContactFragmentAdapter(Context context , List<PersonItemBean> list) {this.list = list;inflater = LayoutInflater.from(context);}@Overridepublic int getGroupCount() {return list.size();}@Overridepublic int getChildrenCount(int groupPosition) {return list.get(groupPosition).getList().size();}@Overridepublic Object getGroup(int groupPosition) {return list.get(groupPosition);}@Overridepublic Object getChild(int groupPosition, int childPosition) {return list.get(groupPosition).getList().get(childPosition).getName();}@Overridepublic long getGroupId(int groupPosition) {return groupPosition;}@Overridepublic long getChildId(int groupPosition, int childPosition) {return childPosition;}@Overridepublic boolean hasStableIds() {return false;}@Overridepublic View getGroupView(int groupPosition, boolean isExpanded,View convertView, ViewGroup parent) {if (convertView == null) {            convertView = inflater.inflate(R.layout.expandablelistview_contacts_fragment_layout_parent, null);        }        TextView tv = (TextView) convertView.findViewById(R.id.parent_textview);        ImageView ivExpandButtonImage  = (ImageView) convertView.findViewById(R.id.expandButtonImage);        tv.setText(list.get(groupPosition).getTitle());                if (ivExpandButtonImage!=null) {            if (isExpanded) { //是否展开            ivExpandButtonImage.setImageResource(R.drawable.vertical);            } else {            ivExpandButtonImage.setImageResource(R.drawable.horizontal);            }        }        return convertView;}@Overridepublic View getChildView(int groupPosition, int childPosition,boolean isLastChild, View convertView, ViewGroup parent) {        if (convertView == null) {            convertView = inflater.inflate(R.layout.expandablelistview_contacts_fragment_layout_children, null);        }        //child 视图的textview        String info = list.get(groupPosition).getList().get(childPosition).getName();        TextView tv = (TextView) convertView.findViewById(R.id.second_textview);        tv.setText(info);        return convertView;}@Overridepublic boolean isChildSelectable(int groupPosition, int childPosition) {return true;}

Java类:

public class ContactsFragment extends Fragment {private String url = "http://192.168.1.176:8080/html/user.html";private ContactFragmentAdapter adapter;//获取到ExpandableListview 控件private ExpandableListView expandableListView;private EditText query;private ImageButton clearSearch;static List<PersonItemBean> list ;@Overridepublic void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);initData();}/** 返回json解析的数据   */private void initData() {try {//请求网络返回的json数据String data = HttpsUtils.readParser(url);//json解析返回的listlist = JsonUtils.getdata(data);Log.d("Dong",list.toString()+ "---");} catch (Exception e) {e.printStackTrace();}adapter = new ContactFragmentAdapter(getActivity(), list);}@Overridepublic View onCreateView(LayoutInflater inflater,@Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {View view = inflater.inflate(R.layout.contacts_fragment, container,false);return view;}@Overridepublic void onActivityCreated(@Nullable Bundle savedInstanceState) {super.onActivityCreated(savedInstanceState);/** 初始化ExpandableListview控件 */expandableListView = (ExpandableListView) getActivity().findViewById(R.id.expandableListView);/** 隐藏ExpandableListview系统默认的箭头 */expandableListView.setGroupIndicator(null);expandableListView.setAdapter(adapter);expandableListView.setOnChildClickListener(new OnChildClickListener() {@Overridepublic boolean onChildClick(ExpandableListView parent, View v,int groupPosition, int childPosition, long id) {Toast.makeText(ContactsFragment.this.getActivity(),"第几"+adapter.getGroupId(groupPosition)+"---总数"+adapter.getGroupCount()+"-----你点击了" +adapter.getGroup(groupPosition)+" 的 --"+adapter.getChild(groupPosition, childPosition),Toast.LENGTH_SHORT).show();EMContact contact = new EMContact("wei");//进入聊天界面Intent chatIntent = new Intent(getActivity(), ChatActivity.class);//chatIntent.putExtra("userId", adapter.getChildId(groupPosition, childPosition));chatIntent.putExtra("userId", contact.getUsername());startActivity(chatIntent);return true;}});}}


javaBean:

/*** * ContactFragment 二级列表中的Bean  * title : group标题 * List: 存放的是child的Person name * @author user * */public class PersonItemBean {private String title;private List<PersonBean> list;//存放Person namepublic String getTitle() {return title;}public void setTitle(String title) {this.title = title;}public List<PersonBean> getList() {return list;}public void setList(List<PersonBean> list) {this.list = list;}}

package com.example.usbisyssafety.domain;import com.easemob.chat.EMContact;/*** * name:child的Person name * @author user * */public class PersonBean extends EMContact{private String name;public PersonBean() {super();}public String getName() {return name;}public void setName(String name) {this.name = name;}@Overridepublic String toString() {return  " | name = " + name;}}



实现效果:完事。



0 0
原创粉丝点击