【问题标题】:Android Studio: Dynamically add buttons in AdapterAndroid Studio:在适配器中动态添加按钮
【发布时间】:2016-03-18 15:28:17
【问题描述】:

我需要帮助为适配器内的 listView 项创建动态按钮。 以下代码是我的适配器getView函数:

@Override
    public View getView(int position, View convertView, ViewGroup parent) {

        if (convertView==null) {
            convertView = getLayoutInflater().inflate(R.layout.sell_animal_list_entry,null);
        }
        Animal animal = (Animal) getItem(position);
        int count = 0;
        int value = 0;
        int age = 0;
        int lifespan = 0;
        int savePosition = 0;
        String name = null;

        lifespan = animal.getLifespan();
        age = animal.getAge();
        value = animal.getValue();
        name = animal.getName();
        savePosition = animal.getPosition();

        LinearLayout buttonLayout = (LinearLayout) convertView.findViewById(R.id.buttonIncludeLayout);
        LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.FILL_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT);
        Button sellButton = new Button(SellAnimalActivity.this);
        sellButton.setText(getResources().getString(R.string.sellAnimalButtonText));
        count = buttonLayout.getChildCount();
        if (count == 0) {
            final int finalSavePosition = savePosition;
            sellButton.setOnClickListener(new View.OnClickListener() {
                public void onClick(View view) {
                    displaySellWarning(finalSavePosition);
                }
            });
            buttonLayout.addView(sellButton, lp);
        }

        return convertView;
    }

我现在的问题是点击按钮时我无法出售正确的动物。 我在列表中有 5 种不同的动物。前 3 只动物正常工作, 但是第 4 和第 5 只动物在出售第一只动物时得到了错误的按钮,即使名称是正确循环的。
编辑: 进一步解释:我的 ListView 布局显示了动物的名称、寿命和年龄,我动态地添加了一个按钮。名称、年龄和寿命已正确应用于每只动物。 该按钮应该出售动物。它适用于列表中的动物 3。但是第 4 和第 5 只动物的按钮试图出售第 1 只动物。 当我 Log.d savePosition 我得到以下值: 0,1,2,0,1,2,0,1,2,0,1,2,0,1,2,3,4 我觉得他只在第 5 个循环时才阅读第 4 和第 5 个条目,这对我来说似乎很奇怪?

在这个问题上花了这么多小时,也许你可以给我这个解决方案的提示,为什么第 4 和第 5 个动物错了?

【问题讨论】:

  • 为什么LinearLayout没有元素时只设置ClickListener?
  • 另外,minimal reproducible example 会很棒。为了查看问题所在,您遗漏了大量代码。
  • 你还需要什么,板球?完整的适配器?
  • 您的问题似乎是(Animal) getItem(position),根据您描述问题的方式,位置 4 和 5 不正确。至少描述一下你所说的get wrong button是什么意思......它们有什么问题,更重要的是——什么会变得正确?
  • 我编辑了上面的条目以进一步解释它,希望这能给你一个更好的主意,我对这个错误感到非常困惑。

标签: android listview button android-studio adapter


【解决方案1】:

由于某种原因我之前没有找到它,当我搜索时,这里有人和我有同样的问题: related question

解决方案也发布在那里。 当 listView 具有 layout:height 的 wrap_content 时,ListView 显然会感到困惑。它需要是fill_parent。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-12-29
    • 2022-01-23
    • 1970-01-01
    • 1970-01-01
    • 2017-11-11
    • 2012-07-29
    • 1970-01-01
    相关资源
    最近更新 更多