当数据在android中动态传递时,无法在ListView中设置每个项目的背景颜色

时间:2014-03-27 08:42:20

标签: android android-listview custom-adapter simpleadapter

我想设置列表的背景颜色,它在文本框中具有不同的值,如来自数据库的快乐,悲伤,我希望在我的文本框中快乐时,背景颜色变为红色,生气时变为绿色像这样...

这是我的代码......

class LoadAllProducts extends AsyncTask<String, String, String> {

        /**
         * Before starting background thread Show Progress Dialog
         * */
        @Override
        protected void onPreExecute() {
            super.onPreExecute();
            pDialog = new ProgressDialog(Feeds.this);
            pDialog.setMessage("Loading Feeds. Please wait...");
            pDialog.setIndeterminate(false);
            pDialog.setCancelable(false);
            pDialog.show();
        }

        /**
         * getting All moods from url
         * */
        protected String doInBackground(String... args) {

            // Session class instance




            // get user data from session
            HashMap<String, String> user = session.getUserDetails();

            // email
            String email = user.get(SessionManage.KEY_EMAIL).toString();

            Log.d("seesion", email);
            // Building Parameters
            List<NameValuePair> para = new ArrayList<NameValuePair>();
            para.add(new BasicNameValuePair("email", email));

            // getting JSON string from URL
            JSONObject json = jParser.makeHttpRequest(url_get_moods, "GET",
                    para);

            // Check your log cat for JSON reponse
            Log.d("All Moods: ", json.toString());

            try {
                // Checking for SUCCESS TAG
                int success = json.getInt(TAG_SUCCESS);
                Log.d("yjyth", Integer.toString(success));

                if (success == 1) {
                    String data = null;
                    // Moods found

                    // looping through All Products
                    for (int i = 1; i <= json.length(); i++) {
                        try {

                            JSONObject c = json.getJSONObject(Integer
                                    .toString(i));

                            Log.d("Loop", Integer.toString(i));
                            Log.d("Value of c", c.toString());

                            JSONObject dd = c.getJSONObject("data");
                            Log.d("value of dta", dd.toString());

                            String type = dd.getString("type");
                            Log.d("value of type", type);

                            String because = dd.getString("because");
                            Log.d("value of type", because);


                            String created = dd.getString("created");
                            Log.d("value of type", type);

                            String description = dd.getString("description");
                            Log.d("value of des", description);

                            //String datetime1 = dd.getString("datetime");
                             img=(ImageView)findViewById(R.id.imageFeeds);
                             LinearLayout l=(LinearLayout)findViewById(R.id.lisfeeds);
                            // creating new HashMap
                            HashMap<String, Object> map = new HashMap<String, Object>();

                            // adding each child node to HashMap key => value

                            map.put("type", type);
                            map.put("because", because);
                            map.put("description", description);
                            map.put("created", created);
                            if(type.equals("Feeling Happy")){
                                map.put("img", R.drawable.happyhov);
                                map.put("color", R.drawable.angrygrad);
                            }
                            else if(type.equals("Feeling Angry")){
                                map.put("img", R.drawable.angryhov);

                            }
                            else if(type.equals("Feeling Confused")){
                                map.put("img", R.drawable.confusdhov);

                            }

                            else if(type.equals("Feeling Confident")){
                                map.put("img", R.drawable.confihov);
                            }

                            else if(type.equals( "Feeling Frustrated")){
                                map.put("img",R.drawable.frusthov);
                            }

                            else if(type.equals("Feeling Lonely")){
                                map.put("img", R.drawable.loneyhov);
                            }
                            else if(type.equals("Feeling Ecstatic")){
                                map.put("img", R.drawable.esthov);
                            }
                            else if(type.equals("Feeling Sad")){
                                map.put("img",R.drawable.sadhov);
                            }


                            // adding HashList to ArrayList
                            moodsList.add(map);
                        } catch (Exception e) {
                            Log.e(" Parser", "Error data " + e.toString());
                        }
                    }
                } else {
                    // no products found
                    // Launch Add New product Activity
                    Intent i = new Intent(getApplicationContext(), Home.class);
                    // Closing all previous activities
                    i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
                    startActivity(i);
                }
            } catch (JSONException e) {
                e.printStackTrace();
            }

            return null;
        }

        /**
         * After completing background task Dismiss the progress dialog
         * **/
        protected void onPostExecute(String file_url) {
            // dismiss the dialog after getting all products
            pDialog.dismiss();
            // updating UI from Background Thread
            runOnUiThread(new Runnable() {
                public void run() {
                    /**
                     * Updating parsed JSON data into ListView
                     * */
            MyAdapter adapter = new MyAdapter(Feeds.this,
                            moodsList, R.layout.item_list, 
                             new String[] {
                    "img",TAG_TYPE,TAG_BECAUSE, TAG_DESCRIPTION, TAG_CREATED},
                            new int[] { R.id.imageFeeds,R.id.type, R.id.texbec, R.id.des,R.id.date });
                    // updating listview
                    lv.setAdapter(adapter);
                }
            });


    }


    }

    class MyAdapter extends SimpleAdapter {

        private String[] names;
        private Activity c;


        public MyAdapter(Context context, List<? extends Map<String, ?>> data,
                int resource, String[] from, int[] to) {
            super(context, data, resource, from, to);
        }

        class ViewHolder {
            public TextView texttype,bec,des,date;
            public ImageView image;
          }

        public MyAdapter(Activity c, String[] names) {
            super(c, moodsList, R.layout.item_list, names, null);
            this.c = c;
            this.names = names;
          }


        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            View vi = convertView;
            Context context = null;
            LayoutInflater inflater = ((Activity) context).getLayoutInflater();
            final ViewHolder holder;
            try {
                if (convertView == null) {
                    vi = inflater.inflate(R.layout.item_list, null);
                    holder = new ViewHolder();
                    holder.texttype = (TextView) vi.findViewById(R.id.type);
                    holder.image = (ImageView) vi
                        .findViewById(R.id.imageFeeds);
                    holder.bec = (TextView) vi.findViewById(R.id.texbec);
                    holder.des = (TextView) vi.findViewById(R.id.des);
                    holder.date = (TextView) vi.findViewById(R.id.date);
                    vi.setTag(holder);
                } else {
                    holder = (ViewHolder) vi.getTag();
                }
                Log.d("fchs","dfvhes");
               //holder.image.setBackgroundResource(TAG_IMAGE);
               holder.texttype.setText(TAG_TYPE);
               holder.bec.setText(TAG_TYPE);
               holder.des.setText(TAG_TYPE);

                if (TAG_TYPE.equals("Happy") ) {
                    vi.setBackgroundColor(Color.BLUE);

                } else {
                    vi.setBackgroundColor(Color.RED);
                }
            }catch(Exception e)
            {

            }
            return vi;
    }
    }

1 个答案:

答案 0 :(得分:0)

在自定义适配器(SimpleAdapter)类中 - &gt;得到 - &gt;公共视图getView方法确保您的代码是使用此

的simmiler
        View vi = convertView;
        final ViewHolder holder;
        try {
            if (convertView == null) {
                vi = inflater.inflate(R.layout.my_group_list_item, null);
                holder = new ViewHolder();
                vi.setTag(holder);
            } else {
                holder = (ViewHolder) vi.getTag();
            }


            if (if sad if happy clause here ) {
                vi.setBackgroundColor(Color.parseColor("#a1cc3b"));

            } else {
                vi.setBackgroundColor(Color.parseColor("#cfd0d1"));
            }

希望这可以帮到你。