【发布时间】:2014-08-06 13:52:20
【问题描述】:
我有一个 ListView 适配器,其中包含每个产品(Listview 行)的名称、价格和 ImageButtons(取消),Listview 有自己的 Onclick 事件,用于编辑单击的产品/行。我的问题是我应该如何将这个 ListView 中的 ImageButtons 的数量(位置)传递回 Fragment,以便我可以删除该行。它困扰了我很长一段时间。这是代码
适配器类receiptListAdapter中的代码(如果需要,我可以粘贴整个代码)
...
ImageButton test = (ImageButton)view.findViewById(R.id.imgBtnDelete);
test.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
test.setTag(position); // this is working and i get the position from the ImageButtons inside dynamic Clickable ListView
}
});
...
来自 Fragment ReceiptItemsFragment 的代码(我想在哪里得到那个号码)
...
public void deleteProduct(int number){
//note: this is working if am calling it from the fragment, but i need it to call from adapter
receiptItemArrayList.remove(number);
TextView txtTotalAmmount = (TextView) getView().findViewById(
R.id.txtReceiptTotalAmmount);
double totalAmmount = getTotalAmmount(receiptItemArrayList);
txtTotalAmmount.setText("Sum: " + String.valueOf(totalAmmount));
receiptListAdapter.notifyDataSetChanged();
}
...
我试过了
喜欢这个((ReceiptItemsFragment)context).deleteProduct(position);
但我得到Cannot cast from Context to ReceiptItemsFragment
我尝试了它是静态的,但后来我无法从 Fragment 运行代码。我是否应该尝试使用接口来传递数据以及如何传递数据(我只知道如何在片段和活动之间做到这一点)?有什么建议吗?
【问题讨论】:
-
它是一个将其转换为上下文的片段。这是错误的。如果您需要片段中的上下文,请使用
getActivity() -
Adapter是在拥有Fragment的Activity里面,还是在一个单独的类中?
-
@tknell 它在单独的类中
-
我找到了答案,我这样做了 stackoverflow.com/a/15444411/1393695</a> 并且成功了
标签: android android-fragments android-listview