我有一个ListView适配器,其中包含每个产品(Listview行)的名称,价格和ImageButton(取消),Listview有它自己的Onclick事件,用于编辑点击的产品/行。我的问题是我应该如何将这个ListView中的数字(位置)ImageButtons传递回一个片段,以便我可以删除该行。它一直困扰着我。下面是代码从ListViews适配器传递数据到片段
从适配器代码类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
}
});
...
从片段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
我尝试了静态的,但是后来我不能运行,从片段中的代码。我应该尝试使用接口来传递数据以及如何(我知道如何在碎片和活动之间做到这一点)?有什么建议么?
其片段它铸造方面。这是错误的。如果需要片段中的上下文,请使用'getActivity()' – Raghunandan
适配器在拥有片段的活动中,还是在单独的类中? – tknell
@tknell它在单独的类 – MePo