更改android listview适配器文件中的imageview

时间:2014-09-22 13:50:54

标签: android listview adapter android-imageview

我试图在android listview中更改图片视图。如果我从列表中选择任何项目行,则有2个图像。他们正在参加,没有参加。

默认情况下,项目状态是参加。如果用户点击参加图像,则功能完成后需要将参加图像更改为不参加。

如果用户点击取消对象图像,则功能将完成,然后需要更改未参加图像以参加图像。

我有以下代码。功能正常。但图像在运行时没有变化。请检查代码并给我一个解决方案。

 public class Today_List_Adapter extends BaseAdapter {

private Activity activity;
static ArrayList<HashMap<String, String>> data;
private static LayoutInflater inflater=null;
AlertDialog.Builder alertDialog;
public ImageLoader imageLoader; 
String success,error;
JSONParser jsonParser = new JSONParser();
public Today_List_Adapter(Activity a, ArrayList<HashMap<String, String>> d) {
    activity = a;
    data=d;
    inflater =  (LayoutInflater)activity.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
public int getCount() {
    return data.size();

}

public Object getItem(int position) {
    return position;
}

public long getItemId(int position) {
    return position;
}

public View getView(int position, View convertView, ViewGroup parent) {
    View vi=convertView;
    if(convertView==null)
        vi = inflater.inflate(R.layout.listof_today, null);

    TextView cartitle = (TextView)vi.findViewById(R.id.today_producttitle);
    ImageView carimage = (ImageView)vi.findViewById(R.id.today_productimage);
    TextView cardate = (TextView)vi.findViewById(R.id.today_productdate);
    TextView cartime = (TextView)vi.findViewById(R.id.today_producttime);
    TextView carddesc = (TextView)vi.findViewById(R.id.today_productdesc);
    final ImageView cardetails = (ImageView)vi.findViewById(R.id.today_productimage_detail);
    ImageView  carcheckin = (ImageView)vi.findViewById(R.id.today_productimage_attend);
    HashMap<String, String> Order = new HashMap<String, String>();
    Order = data.get(position);
    cartitle.setText(Order.get(TodayList.TAG_CAR_TITLE));
    cardate.setText(Order.get(TodayList.TAG_CAR_SDATE)+" "+"-"+" "+Order.get(TodayList.TAG_CAR_EDATE));
    cartime.setText(Order.get(TodayList.TAG_CAR_TIME));
    carddesc.setText(Order.get(TodayList.TAG_CAR_DESC));
    imageLoader=new ImageLoader(activity.getApplicationContext());
    imageLoader.DisplayImage(Order.get(TodayList.TAG_CAR_IMAGE), carimage);
    final String carid = Order.get(TodayList.TAG_CAR_ID);
    final String shareurl = Order.get(TodayList.TAG_CAR_EURL);
    final String plantoattend = Order.get(TodayList.TAG_CAR_STATUS);
    if ((!(LoginForm.GoogleId.equalsIgnoreCase("No user found")))
            || (!(LoginForm.FacebookId.equalsIgnoreCase("No user found")))
            || (!(CommonUtils.login_status
                    .equalsIgnoreCase("No user found")))) {  
        if(plantoattend.equalsIgnoreCase("N")){
        cardetails.setImageResource(R.drawable.attend);
    }
    else {
        cardetails.setImageResource(R.drawable.unattend);
    }
    }
    else {
        cardetails.setImageResource(R.drawable.attend);
    }
    cardetails.setOnClickListener(new View.OnClickListener() {
        public void onClick(View v) {

                    if(plantoattend.equalsIgnoreCase("N")){
    alertDialog = new AlertDialog.Builder(activity);
               alertDialog.setMessage("You're going! Do you want to share the meet?");
    alertDialog.setPositiveButton("Share", new DialogInterface.OnClickListener() {
       public void onClick(DialogInterface dialog, int which) {
           Intent sendIntent = new Intent();
                sendIntent.setAction(Intent.ACTION_SEND);
                sendIntent.putExtra(Intent.EXTRA_TEXT, shareurl);
                sendIntent.setType("text/plain");
         cardetails.setImageResource(R.drawable.unattend);
                activity.startActivityForResult(Intent.createChooser(sendIntent, "Share via"),1000);
       }
      });
    alertDialog.setNegativeButton("Not now", new DialogInterface.OnClickListener() {
    public void onClick(DialogInterface dialog, int which) {
    dialog.dismiss();
    cardetails.setImageResource(R.drawable.unattend);
    new AttendMeet().execute(carid);

    }
    });
    alertDialog.show();
            }
                 else{
                    if (cd.isConnectingToInternet()) {
                     new UnAttendMeet().execute(carid);
                    cardetails.setImageResource(R.drawable.attend);
                    //Today_List_Adapter.this.notifyDataSetChanged();
                    }
                     else {
                    alert.showAlertDialog(activity, "Internet Connection Error",
                            "Please Try Again Later", false);
                    return;
                }
                 }   
        }   
            }   
         });
    carcheckin.setOnClickListener(new View.OnClickListener() {
        public void onClick(View v) {
            Intent sendIntent = new Intent();
            sendIntent.setAction(Intent.ACTION_SEND);
            sendIntent.putExtra(Intent.EXTRA_TEXT, shareurl);
            sendIntent.setType("text/plain");
            activity.startActivity(sendIntent);
        }
     });
    return vi;

   }
  public void onActivityResult(int requestCode, int resultCode, Intent data,String... args) {
    //super.onActivityResult(requestCode, resultCode, data);

    switch(requestCode) {
    case 1000:
      Today_List_Adapter.this.notifyDataSetChanged();
        break;

    }

}

class AttendMeet extends AsyncTask<String, String, String> {
    @Override
    protected void onPreExecute() {
        super.onPreExecute();
    }

    protected String doInBackground(String... args) {
        try {
            List<NameValuePair> params = new ArrayList<NameValuePair>();
            params.add(new BasicNameValuePair("user_id", CommonUtils.login_status));
            params.add(new BasicNameValuePair("event_id", args[0]));
            JSONObject json = jsonParser.makeHttpRequest(url_attendmeet,
                    "POST", params);
            Log.d("Attend Meet", json.toString());
            success = json.getString("status");
             if (success.equalsIgnoreCase("ok")) {
                }
             else
             {
                 error = json.getString("error");
             }
        } catch (JSONException e) {
            e.printStackTrace();
        }

        return null;
    }

    protected void onPostExecute(String file_url) {
         if (success.equalsIgnoreCase("ok")) {

             cardetails.setImageResource(R.drawable.unattend);

                Toast.makeText(activity.getApplicationContext(),
                        "The meet was successfully added on attending meet", Toast.LENGTH_LONG).show();
            }
             else
             {
                 Toast.makeText(activity.getApplicationContext(),
                            error, Toast.LENGTH_LONG).show();
             }

    }

   }
     class UnAttendMeet extends AsyncTask<String, String, String> {
    @Override
    protected void onPreExecute() {
        super.onPreExecute();
    }

    protected String doInBackground(String... args) {
        try {
            List<NameValuePair> params = new ArrayList<NameValuePair>();
            params.add(new BasicNameValuePair("user_id", CommonUtils.login_status));
            params.add(new BasicNameValuePair("event_id", args[0]));
            JSONObject json = jsonParser.makeHttpRequest(url_unattendmeet,
                    "POST", params);
            Log.d("UnAttend Meet", json.toString());
            success = json.getString("status");
             if (success.equalsIgnoreCase("ok")) {

            }
             else
             {
                 error = json.getString("error");
             }
        } catch (JSONException e) {
            e.printStackTrace();
        }

        return null;
    }

    protected void onPostExecute(String file_url) {
         if (success.equalsIgnoreCase("ok")) {
             cardetails.setImageResource(R.drawable.attend);

                Toast.makeText(activity,
                        "The meet was successfully removed from attending meet", Toast.LENGTH_LONG).show();
            }
             else
             {

                 Toast.makeText(activity,
                            error, Toast.LENGTH_LONG).show();
             }

             }
          }

         }

修改

我已更新了我的代码。

现在我已经运行了应用程序。我得到的结果如下:

如果用户单击参加图像,则功能将完成,然后图像从参加图像更改为不参加图像。但是我再次单击未参加图像。,需要打电话给UnAttned类但它只是打电话参加课堂。你可以检查我的代码并给我一个解决方案。

1 个答案:

答案 0 :(得分:1)

如果由于某种原因重新填充视图(例如,调用notifyDataSetChanged(),滚出视图等),则还需要更改基础数据。更改此项以解决紧急问题(订单需要是最终的):

...
cardetails.setOnClickListener(new View.OnClickListener() {
    public void onClick(View v) {

        if (plantoattend.equalsIgnoreCase("N")) {
            alertDialog = new AlertDialog.Builder(activity);
            alertDialog.setMessage("You're going! Do you want to share the meet?");
            alertDialog.setPositiveButton("Share", new DialogInterface.OnClickListener() {
                public void onClick(DialogInterface dialog, int which) {
                    Intent sendIntent = new Intent();
                    sendIntent.setAction(Intent.ACTION_SEND);
                    sendIntent.putExtra(Intent.EXTRA_TEXT, shareurl);
                    sendIntent.setType("text/plain");
                    cardetails.setImageResource(R.drawable.unattend);
                    activity.startActivityForResult(Intent.createChooser(sendIntent, "Share via"), 1000);
                }
            });
            alertDialog.setNegativeButton("Not now", new DialogInterface.OnClickListener() {
                public void onClick(DialogInterface dialog, int which) {
                    dialog.dismiss();
                    Order.put(TodayList.TAG_CAR_STATUS, "Y"); // CHANGE THE UNDERLYING DATA HERE
                    cardetails.setImageResource(R.drawable.unattend);
                     new AttendMeet().execute(carid);

                }
            });
            alertDialog.show();
        } else {
            if (cd.isConnectingToInternet()) {
                new UnAttendMeet().execute(carid);
                Order.put(TodayList.TAG_CAR_STATUS, "N"); // CHANGE THE UNDERLYING DATA HERE
                cardetails.setImageResource(R.drawable.attend);
                //Today_List_Adapter.this.notifyDataSetChanged();
            } else {
                alert.showAlertDialog(activity, "Internet Connection Error",
                              "Please Try Again Later", false);
                return;
            }
        }
    }
});
...

但是,我不想留下这个答案,因为你知道还有很多问题需要解决:

  1. 您不应该像在onPostExecute中那样直接操作ImageView。当AsyncTask完成时,视图可能已被回收并填充其他数据。相反,更改基础数据并在必要时调用informedDataSetChanged。
  2. AsyncTask,没有保持对(multiple!)AsyncTasks的引用意味着,当用户提前离开活动/片段时,您将无法取消它们。这意味着触摸UI的任何内容都会使应用程序崩溃。尽管使用AsyncTasks完全可以执行REST请求,但如果您执行的操作不仅仅是少数请求,那么它很快就会变得复杂。查看Retrofit或Volley等图书馆。
  3. 使用findViewById查找视图很慢并且会导致滚动延迟,请尝试使用ViewHolder模式。
  4. 在地图中存储数据就像你做的那样有点&#34;但是非常非Java-ish并且您必须使用空检查来填充您的代码,否则可能会冒空指针异常。请改用POJO
  5. 坚持命名惯例,让您和其他人更轻松地阅读您的代码。
  6. 我没有查找这些点的链接,但如果需要,我会添加它们。