简体   繁体   English

如何将项目动态添加到列表视图

[英]How to add items to listview dynamically

I am trying create an android app in Android studio that allows me to add items to my listView during runtime. 我正在尝试在Android Studio中创建一个android应用程序,该应用程序允许我在运行时将项目添加到listView中。 I had a code used to add predefined items which worked when but when I modified it to add one item everytime I press the add button, I manage to add the first but when I try to add more after that, all the other items become the same as the first one. 我有一个用于添加预定义项目的代码,该代码在以下情况下有效:但是当我修改它以每次按下添加按钮添加一个项目时,我设法添加第一个项目,但是当我尝试在此之后添加更多项目时,所有其他项目都变为与第一个相同。

Every item has a product id and a amount, in which the idText is set when my apps barcodescanner, scans a product, then I set the amountText by specifying a value in a editText widget and then create a item with these values by pressing the Add button. 每个项目都有一个产品ID和一个量,其中idText设置时,我的应用程序barcodescanner,扫描产品,那么我设置amountText通过在指定值editText widget ,然后按添加创建这些值的项目按钮。 When I use it the first one ends up as it should like this: 当我使用它时,第一个会以如下形式结束:

778216562   12

but when I add another one, all previous items turns into the new one: 但是当我添加另一项时,所有先前的项都变成了新项:

589095564   15
589095564   15

This is the code used to add items to my listView. 这是用于向我的listView添加项目的代码。 The addItem() method is called when I press the add button on the app, also listItem is declared like this List<HashMap<String, String>> listItems = new ArrayList<>(); 当我按下应用程序上的添加按钮时,将调用addItem()方法,并且listItem也这样声明: List<HashMap<String, String>> listItems = new ArrayList<>(); :

 public void addItem(){
        if(amountText.getText().toString().matches("[0-9]+")) {
            productList.put(idText.getText().toString(), amountText.getText().toString());


            SimpleAdapter adapter = new SimpleAdapter(this, listItems, R.layout.list_item,
                    new String[]{"idForID", "idForAmount"},
                    new int[]{R.id.productId, R.id.amount});

            resultsMap.put("idForID", idText.getText().toString());
            resultsMap.put("idForAmount", productList.get(idText.getText().toString()));
            listItems.add(resultsMap);

            productsView.setAdapter(adapter);

        }
    }

Does anyone know how to change this code so I can keep adding items without the previous one changing and while at it I am not able to add an item with the same product id as a previous one, but with a different amount and wonder if anyone knows how to resolve that as well? 有谁知道如何更改此代码,因此我可以继续添加项目而不更改前一个项目,同时我无法添加与前一个项目具有相同产品编号但数量不同的项目,并且怀疑是否有人知道如何解决呢?

Your first issue is because of the way Java handles mutable data types. 您的第一个问题是因为Java处理可变数据类型的方式。 Since the resultsMap is a global variable, when you call put() with the same key value (ie "idForID" and "idForAmount" ) you are overriding the last input for those keys. 由于resultsMap是全局变量,因此当您使用相同的键值(即"idForID""idForAmount" )调用put() ,您将覆盖这些键的最后一个输入。 The reference listItems has still points to the resultsMap object that now contains the overridden data, leaving you with multiple copies of the same object. 引用listItems仍然指向resultsMap对象,该对象现在包含已覆盖的数据,从而使您拥有同一对象的多个副本。

A simple solution to this problem would be to move the declaration of the resultsMap object inside of your addItem() function (making it a local variable). 解决此问题的简单方法是将resultsMap对象的声明移到addItem()函数内部(使其成为局部变量)。 Though I would also advise against this solution, considering the unnecessary added complexity of a Map nested inside of a List . 尽管我也建议不要使用此解决方案,但考虑嵌套在List内的Map不必要的复杂性。

Instead, a solution that would also solve your second issue would be to create a class to contain the data. 相反,也可以解决第二个问题的解决方案是创建一个包含数据的类。

final class Product(String id, String amount) {

    public final String id;
    public final String amount;

    public Product(String id, String amount) {
        this.id = id;
        this.amount = amount;
    }

    /**
     * Override equals() and hashCode() as well.
     * These can be generated in Android Studio by selecting 
     * Code > Generate… > equals() and hashCode().
     */

}

Then use this object as the type for your list and adapter, instead of Map<String, String> , and make sure you create a new object each time you add an item to the list. 然后,将此对象用作列表和适配器的类型,而不是Map<String, String> ,并确保每次向列表中添加项目时都创建一个新对象。 This will allow you to create a List containing any amount of items, even if they have the same id . 这将允许您创建一个包含任意数量的项目的List ,即使它们具有相同的id


As @Raza suggested, I would also recommend switching from a ListView to a RecyclerView . 正如@Raza所建议的那样,我还建议从ListView切换到RecyclerView As stated in the ArrayAdapter documentation. ArrayAdapter文档中所述。

Note: If you are considering using array adapter with a ListView, consider using RecyclerView instead. 注意:如果您考虑将阵列适配器与ListView一起使用,请考虑改为使用RecyclerView。 RecyclerView offers similar features with better performance and more flexibility than ListView provides. 与ListView提供的功能相比, RecyclerView提供了类似的功能,具有更好的性能和更大的灵活性。 See the Recycler View guide. 请参阅《 回收者视图》指南。

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

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