簡體   English   中英

Android 如何為可擴展列表視圖初始化子和父數據

[英]Android how to init child and parent data for expandable listview

向大家問好。 我正在開發一個應用程序,我想在其中實現動態ExpandableListView

客戶端函數

public class ClientFunction extends AppCompatActivity {
    String id, name, mo, city, pin, date, profmail;
    SessionManager session;
    ArrayList<HashMap<String, String>> arraylist;
    ListView orderlist;
    OrderListAdapter adapter;
    String amount, status;
    TextView amt;
    LinearLayout orderempty;
    Dialog dialog;
    List<String> listDataHeader;
    HashMap<String, List<String>> listDataChild;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_client_function);
        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);
        final ActionBar ab = getSupportActionBar();
        assert ab != null;
        ab.setDisplayHomeAsUpEnabled(true);
        ab.setTitle("Orders");
        Intent i = getIntent();
        session = new SessionManager(this);
        HashMap<String, String> user = session.getUserDetails();
        profmail = user.get(SessionManager.KEY_EMAIL);
        orderempty = (LinearLayout) findViewById(R.id.layout_event_empty);
        orderempty.setVisibility(View.GONE);
        id = i.getStringExtra("clientid");
        name = i.getStringExtra("clientname");
        city = i.getStringExtra("address");
        mo = i.getStringExtra("mobileno");
        pin = i.getStringExtra("pincode");
        date = i.getStringExtra("date");
        listDataHeader = new ArrayList<String>();
        listDataChild = new HashMap<String, List<String>>();
        new HttpAsyncTask().execute(SessionManager.getAmateurPath() + "ViewOrder");

    }

    private class HttpAsyncTask extends AsyncTask<String, Void, String> {
        @Override
        protected String doInBackground(String... urls) {
            return POST(urls[0]);
        }

        @Override
        protected void onPostExecute(String result) {
            orderlist = (ListView) findViewById(R.id.order_list);

            // Pass the results into ListViewAdapter.java
            adapter = new OrderListAdapter(ClientFunction.this, arraylist);
            // Set the adapter to the ListView
            orderlist.setAdapter(adapter);
        }
    }

    public String POST(String url) {
        InputStream inputStream;
        String result = "";
        try {
            arraylist = new ArrayList<HashMap<String, String>>();

            HttpClient httpclient = new DefaultHttpClient();
            HttpPost httpPost = new HttpPost(url);

            String json = "";

            JSONObject jsonObject = new JSONObject();
            jsonObject.accumulate("username", profmail);
            jsonObject.accumulate("cid", id);

            json = jsonObject.toString();
            Log.d("JSONStringSend", json);

            StringEntity se = new StringEntity(json);
            httpPost.setEntity(se);

            httpPost.setHeader("Accept", "application/json");
            httpPost.setHeader("Content-type", "application/json");

            HttpResponse httpResponse = httpclient.execute(httpPost);
            inputStream = httpResponse.getEntity().getContent();

            if (inputStream != null) {
                result = convertInputStreamToString(inputStream);
                Log.d("JSONResponce", result);
                String add = "";
                JSONArray jsonArray = new JSONArray(result);
                for (int i = 0; i < jsonArray.length(); i++) {
                    HashMap<String, String> map = new HashMap<String, String>();
                    JSONObject mainjj = new JSONObject((String) jsonArray.get(i));
                    map.put("item", mainjj.getString("item"));
                    map.put("total", mainjj.getString("total"));
                    map.put("orderno", mainjj.getString("orderno"));
                    map.put("quantity", mainjj.getString("quantity"));
                    map.put("extrarate", mainjj.getString("extrarate"));
                    map.put("rate", mainjj.getString("rate"));
                    map.put("detail", mainjj.getString("detail"));
                    arraylist.add(map);
                    listDataHeader.add(mainjj.getString("item"));

                    List<String> mainjj.getString("item") = new ArrayList<String>();
                    mainjj.getString("item").add("Audi");
                    mainjj.getString("item").add("BMW");
                    mainjj.getString("item").add("Honda ");
                    mainjj.getString("item").add("POLO");

                }
                Log.d("ArrayList", arraylist.toString());
                Log.d("ArrayList123456789", "" + listDataHeader.toString());

            }


        } catch (Exception e) {

            Log.d("InputStream", e.getLocalizedMessage());
        }
        return result;
    }

    private String convertInputStreamToString(InputStream inputStream) throws IOException {
        BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
        String line = "";
        String result = "";
        while ((line = bufferedReader.readLine()) != null)
            result += line;
        inputStream.close();
        return result;
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.menu_client_function, menu);
        //        MenuItem item = menu.findItem(R.id.add_order);
        //        SpannableStringBuilder builder = new SpannableStringBuilder("*    Login");
        //        // replace "*" with icon
        //        builder.setSpan(new ImageSpan(this, R.drawable.edit), 0, 1, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
        //        item.setTitle(builder);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        switch (item.getItemId()) {
            case android.R.id.home: {
                finish();
                return true;
            }

            case R.id.profile: {
                Intent ii = new Intent(ClientFunction.this, ViewProfile.class);
                ii.putExtra("clientid", id);
                startActivity(ii);
                break;

            }
            case R.id.add_order: {
                Intent ii = new Intent(ClientFunction.this, AddOrder.class);
                ii.putExtra("clientid", id);
                ii.putExtra("clientname", name);
                ii.putExtra("date", date);
                ii.putExtra("pincode", pin);
                ii.putExtra("address", city);
                ii.putExtra("mobileno", mo);
                startActivity(ii);
                break;

            }
            adapter = new OrderListAdapter(ClientFunction.this, arraylist);
            case R.id.add_payment: {
                dialog = new Dialog(this);
                // dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
                dialog.setContentView(R.layout.addpayment);
                dialog.setTitle(Html.fromHtml("<font color='#FF7F27'>Add Payment</font>"));
                // dialog.getWindow().setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));
                dialog.show();
                amt = (TextView) dialog.findViewById(R.id.amount);
                Button close = (Button) dialog.findViewById(R.id.save);
                close.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        amount = amt.getText().toString();
                        if (amount.length() != 0) {
                            new HttpAsyncTask1().execute(SessionManager.getAmateurPath() + "AddProfessionalPayment");

                        } else {
                            amt.setError("Enter Amount");
                        }
                    }
                });

                break;
            }
        }
        return super.onOptionsItemSelected(item);
    }

    private class HttpAsyncTask1 extends AsyncTask<String, Void, String> {
        @Override
        protected String doInBackground(String... urls) {
            return POST1(urls[0]);
        }

        @Override
        protected void onPostExecute(String result) {
            if (status.equalsIgnoreCase("success")) {
                amt.setHint("Enter Amount");
                dialog.dismiss();
                Toast.makeText(ClientFunction.this, "Amount Added Successfully", Toast.LENGTH_SHORT).show();
            } else
                Toast.makeText(ClientFunction.this, "Amount Added Failed", Toast.LENGTH_SHORT).show();
        }
    }

    public String POST1(String url) {
        InputStream inputStream;
        String result = "";
        try {
            arraylist = new ArrayList<HashMap<String, String>>();

            HttpClient httpclient = new DefaultHttpClient();
            HttpPost httpPost = new HttpPost(url);

            String json = "";

            JSONObject jsonObject = new JSONObject();
            jsonObject.accumulate("username", profmail);
            jsonObject.accumulate("clientid", id);
            jsonObject.accumulate("paymentrs", amount);


            json = jsonObject.toString();
            Log.d("JSONStringSend", json);

            StringEntity se = new StringEntity(json);
            httpPost.setEntity(se);

            httpPost.setHeader("Accept", "application/json");
            httpPost.setHeader("Content-type", "application/json");

            HttpResponse httpResponse = httpclient.execute(httpPost);
            inputStream = httpResponse.getEntity().getContent();

            if (inputStream != null) {
                result = convertInputStreamToString(inputStream);
                Log.d("JSONResponce", result);
                String add = "";
                JSONObject mainjj = new JSONObject(result);
                status = mainjj.getString("status");

            }


        } catch (Exception e) {

            Log.d("InputStream", e.getLocalizedMessage());
        }
        return result;
    }

    public class OrderListAdapter extends BaseAdapter {
        Context context;
        LayoutInflater inflater;
        Button send1;

        ArrayList<HashMap<String, String>> data;
        int lastPosition = 0;
        private ColorGenerator mColorGenerator = ColorGenerator.MATERIAL;

        HashMap<String, String> resultp = new HashMap<String, String>();
        private DisplayImageOptions options;

        public OrderListAdapter(Context context, ArrayList<HashMap<String, String>> arraylist) {
            this.context = context;
            data = arraylist;
        }

        @Override
        public int getCount() {
            if (data.size() == 0) {
                orderempty.setVisibility(View.VISIBLE);
                orderlist.setVisibility(View.GONE);

            }
            return data.size();
        }

        @Override
        public Object getItem(int position) {
            return null;
        }

        @Override
        public long getItemId(int position) {
            return 0;
        }

        @Override
        public View getView(final int position, View convertView, ViewGroup parent) {
            inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);

            View itemView = inflater.inflate(R.layout.inflate_listoforder, parent, false);
            resultp = data.get(position);
            TextView iname = (TextView) itemView.findViewById(R.id.iname);
            TextView iid = (TextView) itemView.findViewById(R.id.iid);
            TextView iqty = (TextView) itemView.findViewById(R.id.iqty);
            TextView itotal = (TextView) itemView.findViewById(R.id.itotal);
            iname.setText("Item Name: " + resultp.get("item"));
            iid.setText("Item Id: " + resultp.get("orderno"));
            iqty.setText("ItemQuantity: " + resultp.get("quantity"));
            itotal.setText("ItemTotal: " + resultp.get("total"));

            itemView.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    resultp = data.get(position);
                    Intent ii = new Intent(ClientFunction.this, ViewOrder.class);
                    ii.putExtra("item", resultp.get("item"));
                    ii.putExtra("clientid", id);
                    ii.putExtra("orderno", resultp.get("orderno"));
                    ii.putExtra("quantity", resultp.get("quantity"));
                    ii.putExtra("total", resultp.get("total"));
                    ii.putExtra("extrarate", resultp.get("extrarate"));
                    ii.putExtra("rate", resultp.get("rate"));
                    ii.putExtra("detail", resultp.get("detail"));
                    startActivity(ii);
                }
            });

            Animation animation = AnimationUtils.loadAnimation(context, (position > lastPosition) ? R.anim.up_from_bottom : R.anim.down_from_top);
            itemView.startAnimation(animation);
            lastPosition = position;
            return itemView;
        }
    }

}

我不知道如何在List<String> listDataHeaderHashMap<String, List<String>> listDataChild添加數據。

我成功地在listDataHeader添加了數據,但我不知道如何將數據動態添加到listDataChild

我在listDataChild添加數據如下

  List<String> mainjj.getString("item") = new ArrayList<String>();
                mainjj.getString("item").add("Audi");
                mainjj.getString("item").add("BMW");
                mainjj.getString("item").add("Honda ");
                mainjj.getString("item").add("POLO");

但它不起作用。 所以請幫我解決一個問題。 這樣我就可以繼續編碼了。 提前致謝。

您的代碼令人困惑,所以我在這里告訴您如何為 ExpandableListView Header 和 Child 添加數據(例如靜態)。

//Function that return Map to add in adapter

public static Map<String, List<String>> getData() 
{
   Map<String, List<String>> expandableList = new TreeMap<>();

   List<String> Child1 = new ArrayList<String>();
   Child1.add("Child data......");

   List<String> Child2 = new ArrayList<String>();
   Child2.add("Child data......");

   List<String> Child3 = new ArrayList<String>();
   Child3.add("Child data........");


   expandableList.put("Header-1", Child1);
   expandableListDetail.put("Header-2",Child2);
   expandableListDetail.put("Header-3",Child3);
   expandableListDetail.put("Header-4",Child4);

   return expandableListDetail;
}

在這里,我只是添加自己的數據,但是對於動態行為,您必須使用循環將數據添加到“expandablList”和“Child”列表。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM