如何制作动态可扩展列表视图?

时间:2017-03-06 12:06:46

标签: android json listview expandablelistview

我正在创建一个动态可扩展列表视图,其中我想在标题(Parent)中显示其标题,而在Parent中显示其他值,这意味着在Child上。我能够从Server获得价值,并希望在Expandable listview中显示这些值。我可以在Header中设置Names但我无法在孩子中显示其他值,我该怎么做才能帮助我。

我正在关注this tutorial

这是活动

中的代码
public class Pxe extends Activity {

    ExpandableListAdapter listAdapter;
    ExpandableListView expListView;
    List<String> listDataHeader;
    HashMap<String, List<String>> listDataChild;
    String myJSON,company_name,from_date,to_date,location,fire_id,guard_number;
    JSONArray peoples = null;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.ex_main);

        // get the listview
        expListView = (ExpandableListView) findViewById(R.id.lvExp);

        // preparing list data
       // prepareListData();
        getProp();

    }




    public void getProp(){
        class GetDataJSON extends AsyncTask<String, Void, String> {
            public void onPreExecute() {
                // Pbar.setVisibility(View.VISIBLE);
            }
            @Override
            protected String doInBackground(String... params) {

                InputStream inputStream = null;
                String result = null;
                try {

                    URL url = new URL("http://xxxxxxxxx/app/guard/guard_history.php");
                    JSONObject postDataParams = new JSONObject();
                    Log.e("Value>>>>>", String.valueOf(postDataParams));
                    postDataParams.put("guard_id", "1");
                    Log.e("params", postDataParams.toString());

                    HttpURLConnection conn = (HttpURLConnection) url.openConnection();
                    conn.setReadTimeout(15000 /* milliseconds */);
                    conn.setConnectTimeout(15000 /* milliseconds */);
                    conn.setRequestMethod("POST");
                    conn.setDoInput(true);
                    conn.setDoOutput(true);
                    OutputStream os = conn.getOutputStream();
                    BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(os, "UTF-8"));
                    writer.write(getPostDataString(postDataParams));

                    writer.flush();
                    writer.close();
                    os.close();

                    int responseCode=conn.getResponseCode();

                    if (responseCode == HttpsURLConnection.HTTP_OK) {

                        BufferedReader in=new BufferedReader(new InputStreamReader(conn.getInputStream()));
                        StringBuilder sb = new StringBuilder("");
                        String line="";
                        while ((line = in.readLine()) != null)
                        {
                            sb.append(line).append("\n");
                        }
                        result = sb.toString();
                    }

                    assert inputStream != null;
                    BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream, "UTF-8"), 8);
                    StringBuilder sb = new StringBuilder();

                    String line = null;
                    while ((line = reader.readLine()) != null)
                    {
                        sb.append(line).append("\n");
                    }
                    result = sb.toString();
                } catch (Exception e) {
                    Log.i("tagconvertstr", "["+result+"]");
                    System.out.println(e);
                }
                finally {
                    try{if(inputStream != null)inputStream.close();}catch(Exception squish){}
                }
                return result;
            }

            @Override
            protected void onPostExecute(String result){

                myJSON = result;
                prepareListData();

            }
        }
        GetDataJSON g = new GetDataJSON();
        g.execute();
    }



    public String getPostDataString(JSONObject params) throws Exception {

        StringBuilder result = new StringBuilder();
        boolean first = true;

        Iterator<String> itr = params.keys();

        while(itr.hasNext()){

            String key= itr.next();
            Object value = params.get(key);

            if (first)
                first = false;
            else
                result.append("&");

            result.append(URLEncoder.encode(key, "UTF-8"));
            result.append("=");
            result.append(URLEncoder.encode(value.toString(), "UTF-8"));

        }
        return result.toString();
    }


    private void prepareListData() {
        listDataHeader = new ArrayList<String>();
        listDataChild = new HashMap<String, List<String>>();
        List<String> top250 = new ArrayList<String>();

        try {
            peoples = new JSONArray(myJSON);
            for(int i=0;i<peoples.length();i++){
                JSONObject c = peoples.getJSONObject(i);

                company_name = c.getString("firm_name");
                from_date = c.getString("joining_date");
                to_date = c.getString("to_date");
                location=c.getString("duty_location");

                listDataHeader.add(company_name);
              //  System.out.println(company_name+" - "+from_date+" - "+to_date+" - "+location);
                top250.add("From Date: "+from_date);
                top250.add("To Date: "+to_date);
                top250.add("Location: "+location);
                listDataChild.put(listDataHeader.get(i), top250);

            }
        } catch (JSONException e) {
            e.printStackTrace();
        }




        // Adding child data
        //listDataHeader.add("Top 250");
        //listDataHeader.add("Now Showing");
      //  listDataHeader.add("Coming Soon..");

        // Adding child data
/*        top250.add("The Shawshank Redemption");
        top250.add("The Godfather");
        top250.add("The Godfather: Part II");
        top250.add("Pulp Fiction");
        top250.add("The Good, the Bad and the Ugly");
        top250.add("The Dark Knight");
        top250.add("12 Angry Men");

        List<String> nowShowing = new ArrayList<String>();
        nowShowing.add("The Conjuring");
        nowShowing.add("Despicable Me 2");
        nowShowing.add("Turbo");
        nowShowing.add("Grown Ups 2");
        nowShowing.add("Red 2");
        nowShowing.add("The Wolverine");

        List<String> comingSoon = new ArrayList<String>();
        comingSoon.add("2 Guns");
        comingSoon.add("The Smurfs 2");
        comingSoon.add("The Spectacular Now");
        comingSoon.add("The Canyons");
        comingSoon.add("Europa Report");*/




        listAdapter = new ExpandableListAdapter(this, listDataHeader, listDataChild);

        // setting list adapter
        expListView.setAdapter(listAdapter);


    }
}  

和ExpandableList Adapter

public class ExpandableListAdapter extends BaseExpandableListAdapter {

    private Context _context;
    private List<String> _listDataHeader; // header titles
    // child data in format of header title, child title
    private HashMap<String, List<String>> _listDataChild;

    public ExpandableListAdapter(Context context, List<String> listDataHeader,
                                 HashMap<String, List<String>> listChildData) {
        this._context = context;
        this._listDataHeader = listDataHeader;
        this._listDataChild = listChildData;
    }

    @Override
    public Object getChild(int groupPosition, int childPosititon) {
        return this._listDataChild.get(this._listDataHeader.get(groupPosition))
                .get(childPosititon);
    }

    @Override
    public long getChildId(int groupPosition, int childPosition) {
        return childPosition;
    }

    @Override
    public View getChildView(int groupPosition, final int childPosition,
                             boolean isLastChild, View convertView, ViewGroup parent) {

        final String childText = (String) getChild(groupPosition, childPosition);

        if (convertView == null) {
            LayoutInflater infalInflater = (LayoutInflater) this._context
                    .getSystemService(Context.LAYOUT_INFLATER_SERVICE);
            convertView = infalInflater.inflate(R.layout.list_item, null);
        }

        TextView txtListChild = (TextView) convertView
                .findViewById(R.id.lblListItem);

        txtListChild.setText(childText);
        return convertView;
    }

    @Override
    public int getChildrenCount(int groupPosition) {
        return this._listDataChild.get(this._listDataHeader.get(groupPosition))
                .size();
    }

    @Override
    public Object getGroup(int groupPosition) {
        return this._listDataHeader.get(groupPosition);
    }

    @Override
    public int getGroupCount() {
        return this._listDataHeader.size();
    }

    @Override
    public long getGroupId(int groupPosition) {
        return groupPosition;
    }

    @Override
    public View getGroupView(int groupPosition, boolean isExpanded,
                             View convertView, ViewGroup parent) {
        String headerTitle = (String) getGroup(groupPosition);
        if (convertView == null) {
            LayoutInflater infalInflater = (LayoutInflater) this._context
                    .getSystemService(Context.LAYOUT_INFLATER_SERVICE);
            convertView = infalInflater.inflate(R.layout.list_group, null);
        }

        TextView lblListHeader = (TextView) convertView
                .findViewById(R.id.lblListHeader);
        lblListHeader.setTypeface(null, Typeface.BOLD);
        lblListHeader.setText(headerTitle);

        return convertView;
    }

    @Override
    public boolean hasStableIds() {
        return false;
    }

    @Override
    public boolean isChildSelectable(int groupPosition, int childPosition) {
        return true;
    }
}

图片enter image description here

3 个答案:

答案 0 :(得分:3)

审核完您的代码后, 改变你的for循环,如:  for(int i = 0; i

RelativeLayout

答案 1 :(得分:0)

你的职能:

prepareListData()

弄得一团糟。

List<String> top250 = new ArrayList<String>();

不在循环中。然后你就可以无限地添加,添加,添加...而无需重新启动列表。

将此行放在循环中,您就完成了:)

答案 2 :(得分:0)

您可以基于动态数据类创建可扩展卡视图。 只需使用MAIN或EXTRA注释其字段即可:

public enum FieldGroup {
MAIN,
EXTRA;

}

公共类ElectricityBillDto扩展BillDto实现Serializable {

@CustomAnnotation(value = FieldGroup.MAIN, title = R.string.name)
@SerializedName("customer_name")
private String customerName;

@CustomAnnotation(value = FieldGroup.MAIN,title = R.string.type)
@SerializedName("company_name")
private String companyName ;

@CustomAnnotation(value = FieldGroup.EXTRA,title = R.string.bill_id)
@SerializedName("bill_identifier")
private String billIdentifier ;

@CustomAnnotation(value = FieldGroup.MAIN,title = R.string.payment_id)
@SerializedName("payment_identifier")
private String paymentIdentifier;

@CustomAnnotation(title = R.string.type)
@SerializedName("company_code")
private int companyCode ;

@CustomAnnotation(title = R.string.phase)
@SerializedName("phase")
private String phase;

@CustomAnnotation(title = R.string.voltage_type)
@SerializedName("voltage_type")
private String voltageType ;

@CustomAnnotation(title = R.string.amper)
@SerializedName("amper")
private String amper;

@CustomAnnotation(title = R.string.contract_demand)
@SerializedName("contract_demand")
private Double contractDemand ;

@CustomAnnotation(title = R.string.tariff_type)
@SerializedName("tariff_type")
private String tariffType;

@CustomAnnotation(title = R.string.customder_type)
@SerializedName("customder_type")
private String customerType ;

@CustomAnnotation(value = FieldGroup.MAIN, title = R.string.family)
@SerializedName("customer_family")
private String customerFamily;

@CustomAnnotation(title = R.string.tel_number)
@SerializedName("tel_number")
private String telNumber ;

@CustomAnnotation(title = R.string.mobile_number)
@SerializedName("mobile_number")
private String mobileNumber;

@CustomAnnotation(title = R.string.service_add)
@SerializedName("service_add")
private String serviceAdd ;

@CustomAnnotation(title = R.string.service_post_code)
@SerializedName("service_post_code")
private String servicePostCode;

@CustomAnnotation(value = FieldGroup.MAIN, title = R.string.total_bill_debt)
@SerializedName("total_bill_debt")
private String totalBillDebt ;

@CustomAnnotation(value = FieldGroup.MAIN, title = R.string.payment_dead_line)
@SerializedName("payment_dead_line_persian")
private String paymentDeadLinePersian ;

@CustomAnnotation(title = R.string.other_account_debt)
@SerializedName("other_account_debt")
private String otherAccountDebt;

@CustomAnnotation(title = R.string.total_register_debt)
@SerializedName("total_register_debt")
private Double totalRegisterDebt;

@CustomAnnotation(title = R.string.location_status)
@SerializedName("location_status")
private String locationStatus;

@CustomAnnotation(value = FieldGroup.MAIN,title = R.string.meter_number)
@SerializedName("serial_number")
private String serialNumber; //todo-z check

@CustomAnnotation(title = R.string.payment_dead_line)
@SerializedName("payment_dead_line")
private Date paymnetDeadLine;

@CustomAnnotation(title = R.string.last_read_date)
@SerializedName("last_read_date")
private Date lastReadDate;

@CustomAnnotation(title = R.string.license_expire_date)
@SerializedName("license_expire_date")
private Date licenseExpireDate;

@CustomAnnotation(title = R.string.lastupdatetime)
@SerializedName("lastupdatetime")
private Date lastupdatetime;

@CustomAnnotation(title = R.string.last_gross_amt)
@SerializedName("last_gross_amt")
private Double LastGrossAmt;

@CustomAnnotation(title = R.string.last_sale_year)
@SerializedName("last_sale_year")
private Double LastSaleYear;

@CustomAnnotation(title = R.string.last_sale_prd)
@SerializedName("last_sale_prd")
private Double LastSalePrd;

@CustomAnnotation(title = R.string.ispaid)
@SerializedName("ispaid")
private Boolean isPaid;

@CustomAnnotation(title = R.string.subscription_id)
@SerializedName("subscription_id")
private Long subscriptionId;

@CustomAnnotation(title = R.string.file_serial_number)
@SerializedName("file_serial_number")
private Long fileSerialNumber;

@CustomAnnotation(title = R.string.x_degree)
@SerializedName("x_degree")
private Double xDegree;

@CustomAnnotation(title = R.string.y_degree)
@SerializedName("y_degree")
private Double yDegree;

@CustomAnnotation(title = R.string.national_code)
@SerializedName("national_code")
private String nationalCode;

public int getCompanyCode() {
    return companyCode;
}

public String getCompanyName() {
    return companyName;
}

public String getPhase() {
    return phase;
}

public String getVoltageType() {
    return voltageType;
}

public String getAmper() {
    return amper;
}

public Double getContractDemand() {
    return contractDemand;
}

public String getTariffType() {
    return tariffType;
}

public String getCustomerType() {
    return customerType;
}

public String getCustomerName() {
    return customerName;
}

public String getCustomerFamily() {
    return customerFamily;
}

public String getTelNumber() {
    return telNumber;
}

public String getMobileNumber() {
    return mobileNumber;
}

public String getServiceAdd() {
    return serviceAdd;
}

public String getServicePostCode() {
    return servicePostCode;
}

public String getTotalBillDebt() {
    return Global.separateAmount(totalBillDebt)+ " " + baseContext.getString(R.string.rial);
}

public String getOtherAccountDebt() {
    return otherAccountDebt;
}

public Double getTotalRegisterDebt() {
    return totalRegisterDebt;
}

public String getLocationStatus() {
    return locationStatus;
}

public String getSerialNumber() {
    return serialNumber;
}

public Date getPaymnetDeadLine() {
    return paymnetDeadLine;
}

public Date getLastReadDate() {
    return lastReadDate;
}

public Date getLicenseExpireDate() {
    return licenseExpireDate;
}

public Date getLastupdatetime() {
    return lastupdatetime;
}

public Double getLastGrossAmt() {
    return LastGrossAmt;
}

public Double getLastSaleYear() {
    return LastSaleYear;
}

public Double getLastSalePrd() {
    return LastSalePrd;
}

public Boolean getPaid() {
    return isPaid;
}

public Long getSubscriptionId() {
    return subscriptionId;
}

public Long getFileSerialNumber() {
    return fileSerialNumber;
}

public Double getxDegree() {
    return xDegree;
}

public Double getyDegree() {
    return yDegree;
}

public String getNationalCode() {
    return nationalCode;
}

public String getPaymentDeadLinePersian() {
    return paymentDeadLinePersian;
}

public String getBillIdentifier() {
    return billIdentifier;
}

public String getPaymentIdentifier() {
    return paymentIdentifier;
}

}

    private void initView(Object object, CardView cardView, LinearLayout lytMain, LinearLayout lytExpandable, Button btnArrowDown) {
    int mainChildIndex = 2;
    int expandableChildIndex = 0;

    // Class
    for (Field field : object.getClass().getDeclaredFields()) {
        field.setAccessible(true);

        String value = null;

        try {
            String methodName = "get" + field.getName().substring(0, 1).toUpperCase() + field.getName().substring(1);

            Method m = object.getClass().getDeclaredMethod(methodName, null);
            Object obj = m.invoke(object);

            value = obj.toString();

            if (value != null && field.getAnnotation(CustomAnnotation.class)!=null) {

                KeyValueView kvView = new KeyValueView(cardView.getContext());
                ViewGroup.LayoutParams layoutParams = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT,
                        ViewGroup.LayoutParams.WRAP_CONTENT);
                kvView.setLayoutParams(layoutParams);

                kvView.setKey(getString(field.getAnnotation(CustomAnnotation.class).title()));
                kvView.setValue(value);

                if (field.getAnnotation(CustomAnnotation.class).value().equals(FieldGroup.MAIN)) {
                    lytMain.addView(kvView, mainChildIndex++);
                }
                if (field.getAnnotation(CustomAnnotation.class).value().equals(FieldGroup.EXTRA)) {
                    lytExpandable.addView(kvView, expandableChildIndex++);
                }
            }
        } catch (Exception e) {
        }
    }
    btnArrowDown.setVisibility(lytExpandable.getChildCount() > 1 ? VISIBLE : GONE);
}