下午好,
所以我有一个自定义 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/