当前位置: 代码迷 >> Android >> 怎么把ArrayList放到button的单击事件里面
  详细解决方案

怎么把ArrayList放到button的单击事件里面

热度:93   发布时间:2016-04-28 02:07:13.0
如何把ArrayList放到button的单击事件里面
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);

ListView lv=(ListView)findViewById(R.id.listView1);

ArrayList<HashMap<String, Object>> listItem = new ArrayList<HashMap<String,Object>>();

HashMap<String, Object> map = new HashMap<String, Object>();
map.put("1", "111");
map.put("2", "222");
map.put("3", "333");
listItem.add(map);

SimpleAdapter mSimpleAdapter=new SimpleAdapter(this,listItem,R.layout.item,new String[]{"1","2","3"},new int[]{R.id.textView1,R.id.textView2,R.id.textView3});
lv.setAdapter(mSimpleAdapter);
}




这是我的代码,运行的话直接显示listview的第一行“111222333”.
我想通过添加一个button,单击button来添加一行,但是我放到button的单击事件里面就报错,像下面这样
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);

ListView lv=(ListView)findViewById(R.id.listView1);

Button btn=(Button)findViewById(R.id.button1);
btn.setOnClickListener(new View.OnClickListener() {

@Override
public void onClick(View v) {
// TODO 自动生成的方法存根
ArrayList<HashMap<String, Object>> listItem = new ArrayList<HashMap<String,Object>>();

HashMap<String, Object> map = new HashMap<String, Object>();
map.put("1", "111");
map.put("2", "222");
map.put("3", "333");
listItem.add(map);

SimpleAdapter mSimpleAdapter=new SimpleAdapter(this,listItem,R.layout.item,new String[]{"1","2","3"},new int[]{R.id.textView1,R.id.textView2,R.id.textView3});
lv.setAdapter(mSimpleAdapter);

}
});


}



求大神帮忙啊
------解决思路----------------------
这个错误应该是语法错误吧。
例如
new SimpleAdapter(this,listItem,R.layout.item,new String[]{"1","2","3"},new int[]{R.id.textView1,R.id.textView2,R.id.textView3});

这个this就是指onclick这个类了,不能直接放进去……写成MainActivity.this(你的activity名.this)
还有ListView lv好像要写全局变量,而不是局部变量……
------解决思路----------------------
楼上正解。还有你这样写也达不到你预期的要求。
你要想实现你的要求,
把这个 
HashMap<String, Object> map = new HashMap<String, Object>();
            map.put("1", "111");
            map.put("2", "222");
            map.put("3", "333");
            listItem.add(map);

SimpleAdapter mSimpleAdapter=new SimpleAdapter(this,listItem,R.layout.item,new String[]{"1","2","3"},new int[]{R.id.textView1,R.id.textView2,R.id.textView3});
        lv.setAdapter(mSimpleAdapter);
拿出来。

but的点击时间这样写
 btn.setOnClickListener(new View.OnClickListener() {
             
            @Override
            public void onClick(View v) {
             
            HashMap<String, Object> map = new HashMap<String, Object>();
            map.put("1", "111");
      
            listItem.add(map);
         
       mSimpleAdapter.notifyDataSetChanged();
                 
            }
        });
  相关解决方案