Android 从适配器自定义类调用 findViewById

标签 android listview adapter findviewbyid

下午好,

所以我有一个自定义 ListView 和一个自定义适配器,其中有一个项目是每行的复选框。在我的 getView 中,我为复选框实现了 setOnCheckedChangeListener 和 onCheckedChanged 处理程序。

现在的问题是:

每当我选中/取消选中列表中的一项时,我想用我想要的值更新外部 TextView (假设每个项目都有一个关联的价格,所以我想在列表下方显示总价) .

我应该如何从适配器的 getView 到达“外部” View ?我还有什么其他解决方法?

我在自定义适配器的 getView 函数上留下了部分代码:

CheckBox name = (CheckBox) view.findViewById(R.id.product);
    name.setText(content[i][0]);
    final View v = view;
    final int position = i;
    name.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
        @Override
        public void onCheckedChanged(CompoundButton group, boolean isChecked) {
            setCheckedItem(position);
            EditText quantity = (EditText) v.findViewById(R.id.product_quantity);
            content[position][3] = quantity.getText().toString();
            Iterator<String> it = getCheckedItems().values().iterator();
            Double total = 0.0;
            for (int i=0;i<getCheckedItems().size();i++){
                Integer quantity_p = Integer.parseInt(getItem(position)[3]);
                Double price = Double.parseDouble(getItem(position)[2]);
                total += quantity_p*price;
            }
            TextView total_price = (TextView) findViewById(R.id.total_products_price);
            total_price.setText(total.toString());
        }
    });

注意最后两行:我知道我无法调用 findViewById 但我现在不知道该怎么办。任何建议都很好,谢谢。

最佳答案

将适配器类放入 Activity 类中。 在主 Activity 类中声明 TextViewtotal_price 然后

total_price = (TextView) findViewById(R.id.total_products_price);

在你的创建中。 然后您可以在onCheckedChanged内访问total_price。试试这个,也许有用。

关于Android 从适配器自定义类调用 findViewById,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26734472/

相关文章:

java - 如何将 int 转换为在 textView 内设置

c# - 删除 ListView 中的项目

android-studio - 滚动时选定的图像按钮会更改其在 recyclerView 中的位置

android - 如何将图像加载到 ListView 适配器中的正确行

android - Android什么时候检查Min-sdk?

Android SKIA 图像解码

java - 从 Android 中的 SQLite 数据库填充 ListView

android - 显示空列表的 SimpleAdapter

android - 如何在 PagerAdapter 中更新 textview(在 instantiateItem 中使用 inflater 之后)

android - 修改android :exported programmatically