Use checkbox in listview and get the value of them android

时间:2015-11-12 10:47:20

标签: android checkbox android-listview

I am developing an app that get pictures from a server by j-son and show them to user in a list-view that they can choose some pic for download by check-box.

I want to use 2 array-list:

  • one for the pic urls
  • another one for check-box value

My problem is I don't know much about list-views. check-box of special row must change when user click on that row, and how to get the check-box value from list-view (more important).

 void pics(JSONArray data){
   String url;int i;
   for (i=0;i<data.length();i++){
       try {
           String u=data.getJSONObject(i).getJSONObject("images").getJSONObject("res2").getString("url");
           String t=data.getJSONObject(i).getJSONObject("images").getJSONObject("resolution1").getString("url");
           myList.add(t);
           Lists.add(u);
           url=data.getJSONObject(i).getString("type");
         if (url.equals("video"))
             continue;
    } catch (JSONException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
   }
   try {
    if(i<data.length()){
       String t=data.getJSONObject(i).getJSONObject("videos").getJSONObject("standard_resolution").getString("url");
       myList.set(i, t);}
    else{


    }
   } catch (JSONException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
}


}

2 个答案:

答案 0 :(得分:0)

您可以制作ModelClass ImageData

class ImageData {
   private String url;
   private boolean isChecked;

   public void setChecked(boolean checked) {
       this.ischecked         = checked;
   }

   public void setUrl(String url) {
       this.url               = url;
   }

   public boolean isChecked() {
       return ischecked;
   }

   public String getUrl() {
       return url;
   }
}

将json保存在此模型类中并添加到arraylist。在适配器中传递此内容并相应地绑定视图。当用户单击列表项时,更改相应模型类的isChecked值。可以在baseadapter类的getView方法

中处理Click事件

如果实现了listitemclick,则设置

android:focusable="false"
android:focusableInTouchMode="false"
XML中的

答案 1 :(得分:0)

您可以使用@SKT建议的模型来实现这一目标。 您可以将图像数据类型列表创建为 -

List<ImageData> imagedatas= new ArrayList<>();

现在,您可以将for循环中的图像数据实例添加为 -

ImageData imageData = new ImageData();
imageData.setUrl(u);

现在您需要创建自定义适配器(如果尚未创建),并且需要在OnCheckedChangeListener上设置选中的CheckBox,并且需要相应地修改ImageData模型的值。