简体   繁体   English

如何通过单击每个按钮将多个项目添加到ListView

[英]How to add multiple item to a ListView with each Button click

I found much on google but not able to get the answer. 我在Google上发现了很多东西,但无法获得答案。 I got How to add an item to a ListView with each Button click . 我得到了如何通过单击每个按钮将项目添加到ListView的方法 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 1)将两个数据都添加到数组中

2) notify data set changes 2)通知数据集更改

// 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. 尝试在按钮的onClick内使用dataArray.add(dataField)并将更改通知给适配器。 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++;
    });

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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