二級列表ExpendableListView實現從網絡上獲取數據

android端獲取網絡數據添加到二級列表ExpandableListView實例

效果如下圖所示:

這裏寫圖片描述

(個人使用 禁止商業使用)

1.首先創建二級列表的JavaBean類 ;

2.訪問網址請求數據,使用Gson解析json串,代碼如下:

public class ExUtils {

    private static final String TAG_GET = "exutils--->";

    public static String connectGet() {

        HttpURLConnection urlConnection = null;
        try {
            URL url = new URL("http://www.handybest.com/index.php?m=Wx&c=Index&a=get_topic_info&id=34&view=");
            urlConnection = (HttpURLConnection) url.openConnection();
            InputStream in = new BufferedInputStream(urlConnection.getInputStream());
            // 判斷請求是否成功
            if (urlConnection.getResponseCode() == 200) {
//                // 獲取返回的數據
                return readInStreams(in);
            } else {
                Log.i(TAG_GET, "Get方式請求失敗");
            }

        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            urlConnection.disconnect();
        }
        return null;
    }

    private static String readInStreams(InputStream in) {
        Scanner scanner = new Scanner(in).useDelimiter("\\A");
        return scanner.hasNext() ? scanner.next() : "";
    }

    /**
     * 模擬數據-先使用本地json數據
     *
     * @return
     */
    private String getJson() {

        //Json數據的讀寫
        try {
//            InputStream is = this.getAssets().open("test.json");//eclipse
            InputStream is = getClass().getClassLoader().getResourceAsStream("assets/" + "data.json");//android studio
            BufferedReader bufr = new BufferedReader(new InputStreamReader(is));
            String line;
            StringBuilder builder = new StringBuilder();
            while ((line = bufr.readLine()) != null) {
                builder.append(line);
            }
            is.close();
            bufr.close();

            return builder.toString();
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();

        }
        return "";
    }

    /***
     * Gson 解析數據
     */
    public LcBean gsonData() {

        String strContentSS = getJson();
        LcBean lcBean = null;
        try {
            //String strContent = connectGet();
            Gson gson = new Gson();

            lcBean = gson.fromJson(strContentSS, LcBean.class);
            return lcBean;
        } catch (JsonSyntaxException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return null;
    }
}

3.最重要的功能塊出現,實現一級列表,二級列表數據的添加:

1)爲一級列表添加數據方法:

  /**一級列表數據**/
            public ArrayList<String> getGeneralsTypes() {
                ArrayList<String> generalsTypes = new ArrayList<String>();
                for (int i = 0; i < detailsList.size(); i++) {

                    generalsTypes.add(detailsList.get(i).getTag_title());
                }
                return generalsTypes;

            }

            private ArrayList<String> generalsTypes = getGeneralsTypes();

2)爲二級列表添加數據

public ArrayList<ArrayList<DetailsBean.PictBean>> getGenerals(){
             // Objects[][] objectsesGener=new Objects[detailsList.size()][];
              ArrayList<ArrayList<DetailsBean.PictBean>> generalss = new  ArrayList<ArrayList<DetailsBean.PictBean>>();
              for (int i=0;i<detailsList.size();i++){
                  DetailsBean detailsBean = detailsList.get(i);
                  List<DetailsBean.PictBean> pict = detailsBean.getPict();
                  ArrayList<DetailsBean.PictBean> dpict=new ArrayList<DetailsBean.PictBean>();
                  for (int j=0;j<pict.size();j++){
                      dpict.add(pict.get(j));
                  }
                  generalss.add(dpict);
              }
              Log.i("exutils---2>",generalss.toString());
              return generalss;

          }
          private ArrayList<ArrayList<DetailsBean.PictBean>> generals=getGenerals();

4.ExpandableListAdapter中的實現如下:

      final ExpandableListAdapter adapter = new BaseExpandableListAdapter() {
          //設置組視圖的圖片
//          int[] logos = new int[] { R.drawable.ic_launcher, R.drawable.ic_launcher,R.drawable.ic_launcher};

          //          private String [][] generals=ExUtils.getItemChild();
          //子視圖圖片
          /*public int[][] generallogos = new int[][] {
                  { R.drawable.ic_launcher, R.drawable.ic_launcher,
                          R.drawable.ic_launcher, R.drawable.ic_launcher,
                          R.drawable.ic_launcher, R.drawable.ic_launcher },
                  { R.drawable.ic_launcher, R.drawable.ic_launcher,
                          R.drawable.ic_launcher, R.drawable.ic_launcher,
                          R.drawable.ic_launcher, R.drawable.ic_launcher },
                  { R.drawable.ic_launcher, R.drawable.ic_launcher, R.drawable.ic_launcher,
                          R.drawable.ic_launcher, R.drawable.ic_launcher } };*/

          public List<DetailsBean>  detailsList= ExUtils.gsonData().getData().getDetails();
            /**一級列表數據**/
          public ArrayList<String> getGeneralsTypes(){
              ArrayList<String> generalsTypes=new ArrayList<String>();
              for(int i=0;i<detailsList.size();i++){

                generalsTypes.add(detailsList.get(i).getTag_title());
            }
            return generalsTypes;

          }
          private ArrayList<String> generalsTypes=getGeneralsTypes();

          /**二級列表數據**/
          public ArrayList<ArrayList<DetailsBean.PictBean>> getGenerals(){
             // Objects[][] objectsesGener=new Objects[detailsList.size()][];
              ArrayList<ArrayList<DetailsBean.PictBean>> generalss = new  ArrayList<ArrayList<DetailsBean.PictBean>>();
              for (int i=0;i<detailsList.size();i++){
                  DetailsBean detailsBean = detailsList.get(i);
                  List<DetailsBean.PictBean> pict = detailsBean.getPict();
                  ArrayList<DetailsBean.PictBean> dpict=new ArrayList<DetailsBean.PictBean>();
                  for (int j=0;j<pict.size();j++){
                      dpict.add(pict.get(j));
                  }
                  generalss.add(dpict);
              }
              Log.i("exutils---2>",generalss.toString());
              return generalss;

          }
          private ArrayList<ArrayList<DetailsBean.PictBean>> generals=getGenerals();



          //自己定義一個獲得文字信息的方法
          TextView getTextView() {
              AbsListView.LayoutParams lp = new AbsListView.LayoutParams(
                      ViewGroup.LayoutParams.FILL_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT);
              TextView textView = new TextView(
                      MainActivity.this);
              textView.setLayoutParams(lp);
              textView.setGravity(Gravity.CENTER_VERTICAL);
              textView.setPadding(36, 0, 0, 0);
              textView.setTextSize(20);
              textView.setTextColor(Color.BLACK);
              return textView;
          }


          //重寫ExpandableListAdapter中的各個方法
          @Override
          public int getGroupCount() {
              // TODO Auto-generated method stub
              return generalsTypes.size();
          }

          @Override
          public Object getGroup(int groupPosition) {
              // TODO Auto-generated method stub
              return generalsTypes.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 generals.get(groupPosition).size();
          }

          @Override
          public DetailsBean.PictBean getChild(int groupPosition, int childPosition) {
              // TODO Auto-generated method stub
              return    generals.get(groupPosition).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) {
              // TODO Auto-generated method stub
              LinearLayout ll = new LinearLayout(
                      MainActivity.this);
//              ll.setOrientation(0);
              ImageView logo = new ImageView(MainActivity.this);
//              logo.setImageResource(logos[groupPosition]);
              logo.setPadding(50, 0, 0, 0);
              ll.addView(logo);
              TextView textView = getTextView();
              textView.setTextColor(Color.BLACK);
              textView.setText(getGroup(groupPosition).toString());
              ll.addView(textView);

              return ll;
          }

          @Override
          public View getChildView(int groupPosition, int childPosition,
                                   boolean isLastChild, View convertView, ViewGroup parent) {
              // TODO Auto-generated method stub
              LinearLayout ll = new LinearLayout(
                      MainActivity.this);
//              ll.setOrientation(0);
//              ImageView generallogo = new ImageView(
//                      MainActivity.this);
//              generallogo
//                      .setImageResource(generallogos[groupPosition][childPosition]);
//              ll.addView(generallogo);
              TextView textView = getTextView();
              textView.setText(getChild(groupPosition, childPosition).getContent());
              ll.addView(textView);

              Log.i("exutils---1>","groupPosition+childPosition=["+groupPosition+","+childPosition+"]");
              Log.i("exutils---1>",getChild(groupPosition, childPosition).getContent());
              return ll;
          }

          @Override
          public boolean isChildSelectable(int groupPosition,
                                           int childPosition) {
              // TODO Auto-generated method stub
              return true;
          }

      };
  1. 最後在MainActivity中將數據添加到視圖view上顯示出來:
 ExpandableListView expandableListView = (ExpandableListView) findViewById(R.id.list);
      expandableListView.setAdapter(adapter);


      //設置item點擊的監聽器
      expandableListView.setOnChildClickListener(new ExpandableListView.OnChildClickListener() {

          @Override
          public boolean onChildClick(ExpandableListView parent, View v,
                                      int groupPosition, int childPosition, long id) {

              Toast.makeText(
                      MainActivity.this,
                      "你點擊了" + adapter.getChild(groupPosition, childPosition),
                      Toast.LENGTH_SHORT).show();

              return false;
          }
      });
      }

代碼下載地址:點我

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章