2011-11-09 36 views
1

我在复选框的帮助下创建了具有多个选择的自定义列表。最后,我设法在列表的项目选择事件上设置了复选框。在android中定制列表视图

但是当我的复选框没有按照列表的选择被选中时 当我点击第一行第4行的复选框时会自动点击。总之序列不被维护。 与我工作的代码如下

ListAdapter adapter = new SimpleAdapter(
        this, 
        Datalist , 
        R.layout.customlist, 
        new String[] {"fileName","contentLength","keyPath"}, 
        new int[] {R.id.title,R.id.size, R.id.path} 
); 
      setListAdapter(adapter); 

protected void onListItemClick(ListView l, View v, int position, long id) { 
      super.onListItemClick(l, v, position, id); 
      ViewGroup group=(ViewGroup)v; 
     CheckBox check=(CheckBox)group.findViewById(R.id.sharecheckbox); 
     check.toggle(); 
} 
+0

http://stackoverflow.com/questions/7738527/getting-an-issue-while-checking-the-dynamically-generated-checkbox-through-list/7739006#7739006 – MKJParekh

+0

检查本教程在这里给定定制列表的很好例子。 [http://www.vogella.de/articles/AndroidListView/article.html](http://www.vogella.de/articles/AndroidListView/article.html) – Pratik

回答

1
ListView mainListView; 
    mainListView = (ListView) findViewById(R.id.mainListView); 

    // Create and populate a List of planet names. 
    String[] planets = new String[] { "Mercury", "Venus", "Earth", "Mars", 
             "Jupiter", "Saturn", "Uranus", "Neptune"};  
    ArrayList<String> planetList = new ArrayList<String>(); 
    planetList.addAll(Arrays.asList(planets)); 

    // Create ArrayAdapter using the planet list. 
    listAdapter = new ArrayAdapter<String>(this, R.layout.simplerow, planetList); 

    // Add more planets. If you passed a String[] instead of a List<String> 
    // into the ArrayAdapter constructor, you must not add more items. 
    // Otherwise an exception will occur. 
    listAdapter.add("Ceres"); 
    listAdapter.add("Pluto"); 
    listAdapter.add("Haumea"); 
    listAdapter.add("Makemake"); 
    listAdapter.add("Eris"); 

    // Set the ArrayAdapter as the ListView's adapter. 
    mainListView.setAdapter(listAdapter);   
    } 
} 
1

ListView控件用来维护列表项重用,按照从谷歌I/O这相当细致explanation

因此,check在列表中的特定项目不会保持不变(即如果ListView重绘它或可能检查其他项目,它可能会被取消选中)。

我会建议保持自己的检查状态阵列(将其设定值在onListItemClick()):

  • 保持自己在Datalist“器isChecked”,并使用自己的SimpleAdapter.ViewBinder来设置适当的复选框状态每次setViewValue()叫;
  • 扩展ArrayAdapter并检查了getView()中绑定的状态;