【问题标题】:change imageview in android listview adapter file更改 android listview 适配器文件中的 imageview
【发布时间】:2014-09-22 13:50:53
【问题描述】:

我试图更改 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 类.但它只调用出席类。请您检查我的代码并给我一个解决方案。

【问题讨论】:

  • 您是否在单击图像时调试cardetails.setImageResource 代码正在执行?
  • @MysticMagic 收到敬酒消息““参加会议时已成功添加会议。但图像尚未更改。
  • 在调用setImageResource 后尝试调用yourAdapter.notifyDataSetChanged();
  • @MysticMagic 是的,我也试过了。但屏幕闪烁(刷新)。但图像尚未改变......但我已经验证功能已完成。因为如果我刷新了整个活动,则图像已更改。
  • 哦..然后检查this是否有帮助..

标签: android listview adapter android-imageview


【解决方案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 完成时,视图可能已被回收并填充了其他数据。相反,更改基础数据并在必要时调用 notifyDataSetChanged。
  2. AsyncTask,不保留对(多个!)AsyncTasks 的引用意味着,当用户提前离开活动/片段时,您将无法取消它们。这意味着任何接触 UI 的东西都会使应用程序崩溃。虽然使用 AsyncTasks 执行 REST 请求是绝对可能的,但如果您执行的请求不止几个,它会很痛苦并且会很快变得复杂。查看 Retrofit 或 Volley 等库。
  3. 使用 findViewById 查找视图很慢并且会导致滚动滞后,请尝试 ViewHolder 模式。
  4. 像您所做的那样在 Map 中存储数据“有点”,但非常不符合 Java 风格,您必须在代码中添加空值检查,否则会冒空指针异常的风险。改用 POJO
  5. 遵守命名约定,让您和其他人更容易阅读您的代码。

我没有查找这些点的链接,但如果需要,我会添加它们。

【讨论】:

  • 在您的情况下,您无法将不同的 HashMap 重新分配给 Order,但您仍然可以更改 HashMap 中的键值。
  • 我看到了你的问题。 HashMap&lt;String, String&gt; Order = new HashMap&lt;String, String&gt;(); Order = data.get(position); 没有意义,就用final HashMap&lt;String, String&gt; Order = data.get(position)
  • 是的...谢谢您的帮助...非常感谢...activity.startActivityForResult(Intent.createChooser(sendIntent, "Share via"), 1000);此功能未在我的适配器文件中调用...如果可能,您检查了吗?
  • 解决了这个问题。非常感谢 :)
猜你喜欢
  • 2014-11-27
  • 1970-01-01
  • 2016-11-25
  • 2019-09-16
  • 1970-01-01
  • 1970-01-01
  • 2020-06-25
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多