简体   繁体   中英

How to add a item in List View at run time

I am new at Android and have a list to add and remove items at run time.
I am using the following code to add a new item:

public class MainActivity extends Activity {

private ListView list;
private Button btAdd;
private ArrayAdapter<String[]> adapter;


@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    list=(ListView)this.findViewById(R.id.ListView1);
    btAdd=(Button)this.findViewById(R.id.button1);
    String [] name={"new Item"};
    adapter=new ArrayAdapter<String[]>(this,R.id.ListView1);
    adapter.add(name);


    btAdd.setOnClickListener(new OnClickListener()
    {
        public void onClick(View v)
          {
            list.setAdapter(adapter);
          }

    });   

}

What is the problem with this?

1) set your adapter in onCreate: list.setAdapter(adapter);

2) Add//Remove your item in your OnClickListener and then call adapter.notifyDatasetChanged()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM