【问题标题】:repeating ListView重复列表视图
【发布时间】:2011-07-22 11:50:48
【问题描述】:

大家好,我正在努力在listview 上显示项目列表,我正在使用的代码是

public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.custom_list_view);
        ListView lv= (ListView)findViewById(R.id.listview);
        rtrnList = new ArrayList<HashMap<String,String>>();
        getmyLocation();
        listclass = new listClass(offersobj);
        listclass.populate();
        rtrnList = listclass.getListArray();
        adapter = new SimpleAdapter(
                this,
                rtrnList,
                R.layout.custom_row_view,
                new String[] {"Name","Msg","time"},
                new int[] {R.id.text1,R.id.text2, R.id.text3}
                );

        lv.setAdapter(adapter);
    }

问题是我要显示三个名字 Avinash、Arun、Rajesh。当应用程序启动时,这三个名称显示在列表中。当我关闭并再次启动应用程序时,值会重复 Avinash、Arun、Rajesh、Avinash、Arun、Rajesh。我无法弄清楚如何解决这个问题。

【问题讨论】:

  • 每次打开列表视图时,将数组列表 rtrnList 清空并重新加载。

标签: android android-layout listactivity


【解决方案1】:

您显示的代码看起来不错。我的猜测是 listclass.populate() 修改了 offersobj 并且 offersobj 在您的活动的多个创建中被重用。因此,无论何时创建活动,都会填充其他数据。

【讨论】:

  • 感谢乔纳斯的回复。一些调试工作解决了这个问题。
【解决方案2】:
public class ListViewA extends Activity {
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        ListView lv= (ListView)findViewById(R.id.listview);

        // create the grid item mapping
        String[] from = new String[] {"rowid", "col_1", "col_2", "col_3"};
        int[] to = new int[] { R.id.item1, R.id.item2, R.id.item3, R.id.item4 };

        // prepare the list of all records
        List<HashMap<String, String>> fillMaps = new ArrayList<HashMap<String, String>>();
        for(int i = 0; i < 10; i++){
            HashMap<String, String> map = new HashMap<String, String>();
            map.put("rowid", "" + i);
            map.put("col_1", "col_1_item_" + i);
            map.put("col_2", "col_2_item_" + i);
            map.put("col_3", "col_3_item_" + i);
            fillMaps.add(map);
        }

        // fill in the grid_item layout
        SimpleAdapter adapter = new SimpleAdapter(this, fillMaps, R.layout.grid_item, from, to);
        lv.setAdapter(adapter);
    }
}

更多示例see this link
this also
listview about adapter, for create a hashmap, why bitmap type imported cannot show image in listview?
What adapter shall I use to use HashMap in a ListView

【讨论】:

  • 感谢您的回复。一些调试工作解决了这个问题。
猜你喜欢
  • 1970-01-01
  • 2021-12-06
  • 1970-01-01
  • 1970-01-01
  • 2016-09-27
  • 2014-06-24
  • 1970-01-01
  • 2013-09-22
  • 2018-11-15
相关资源
最近更新 更多