简体   繁体   中英

how to add an item to a listView whithout changing other Items

I'm beginner in android and i want to add an item to a ListView when i click on a button. but when i do that, the ListView restarts and all the previous changes i made disappear. how can i save the previous state of the ListView.

This is the MainActivity:

protected void onCreate(Bundle savedInstanceState) {
   super.onCreate(savedInstanceState);
   setContentView(R.layout.activity_main);
   listMarks = (ListView) findViewById(R.id.list_marks);
   btn_add = (Button) findViewById(R.id.btn_add);
   final Mark mark = new Mark("", "", "", "");
   final ArrayList<Mark> marks = new ArrayList<Mark>();
   marks.add(marks.size(), mark);
   adapter = new MarkLitViewAdapter(MainActivity.this, marks);
   listMarks.setAdapter(adapter);
   btn_add.setOnClickListener(new View.OnClickListener() {
      @Override
      public void onClick(View v) {
         marks.add(mark);
         adapter.notifyDataSetChanged();
      }
   });
}

I made this changes but when click on add button an item is being add but previous changes disappear this is when i click on the add button

Instead of doing adapter.insert(mark, marks.size()); you can use the adapter.notifyDataSetChanged(); functionality. Remove the final from here final ArrayList<Mark> marks = new ArrayList<Mark>(); and insert your Mark into this ArrayList and then do adapter.notifyDataSetChanged() inside the OnClickListener

First off, I strongly suggest you use RecyclerView instead of ListView, if you aren't already. It's a categorically better version of ListView.

The function you are looking for is notifyItemInserted .

I wrote up a very simple example in Kotlin (also suggested learning if you want to continue in Android development, since it's the officially supported language now.)

The relevant snippet is below. Create an addItem function in your adapter which uses notifyItemInserted :

fun addItem(value: String) {
    items.add(value)
    notifyItemInserted(items.size)
}

And then in your button OnClickListener call that adapter function to add a new item.

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