简体   繁体   中英

How to add multiple item to a ListView with each Button click

I found much on google but not able to get the answer. I got How to add an item to a ListView with each Button click . here we are learning to add single item.. thanks in advance

Any reason why you can't try the following?

@Override
public void onClick(View v) {
    myDataArray.add(data1);
    myDataArray.add(data2);
    myAdapter.notifyDataSetChanged();
}

Just like in the answer provided in the question you've shared, to add two items -

1) add both the data to the array

2) notify data set changes

// Add the data fields to the array
dataArray.add(0, dataField1);
dataArray.add(1, dataField2);
// Notify the adapter that data set has changed
adapter.notifyDataSetChanged();

Try dataArray.add(dataField) inside the button's onClick and notify the adapter about the changes. Every time the button is clicked, an item gets added at the end of the list.

So if you want to do this statically

ListView<String> list = new ListView<String>();
    ObservableList<String> items = FXCollections.observableArrayList(
            "something1", "something2", "something3");
    list.setItems(items); 

But if you want to do this dinamically you can use this code:

ListView<String> list = new ListView<String>();
    ObservableList<String> items = FXCollections.observableArrayList(
            "something1", "something2", "something3");
    list.setItems(items);

 list.setEditable(true);

    Button btn = new Button();
    btn.setText("Add String");
    btn.setOnAction((ActionEvent event) -> {
        list.getItems().add(i - 1, "something" + i);
        list.edit(i - 2);
        i++;
    });

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