2

I have a ListView Adapter in which are names, prices and ImageButtons (of Cancel) for every product(Listview row), Listview has its own Onclick Event which is used to edit clicked Product/Row. My question is how should I pass a number(position) of ImageButtons that are in this ListView back to a Fragment so i can delete that row. its been bothering me for quite a while. Here is the code

Code from Adapters Class receiptListAdapter ( i can paste whole code if necessary )

...

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

            }

          });      

...

Code from Fragment ReceiptItemsFragment (Where i want to get that number)

...  
 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();

    }
...

I tried

like this ((ReceiptItemsFragment)context).deleteProduct(position);

but i get Cannot cast from Context to ReceiptItemsFragment

I tried it static but then I cant run the code from Fragment. Should I try to use Interface to pass data and how (i know only how to do that between fragments and activity)? any suggestions?

MePo
  • 1,044
  • 2
  • 23
  • 48

1 Answers1

0

I'd suggest you let your Activity implement AdapterView.OnItemClickListener and add it as a Listener to your ListView. Inside the Activity:

listView.setOnItemClickListener(this);

And from the Activty, you can simply call the method on the fragment:

@Override
onItemClick(AdapterView<?> parent, View view, int position, long id){
    //something like this, to get the product id
    deleteProduct(listView.getAdapter().getItem(position).getId());
}
tknell
  • 9,007
  • 3
  • 24
  • 28
  • I think i wrote it a bit unclear, i will explain what i want to do. I have a Listview which has an adapter, and in that adapter i have Product name, Product price, Product ammount and ImageButtonsfor every row and they are dynamically created. What i want to do is get the position number of a row on ImageButton click and then pass that number to Fragment so i can delete that row with `deleteProduct (int number)` . I do get that number, but i cant figure out how to pass that number back to Fragment – MePo Jun 16 '14 at 18:05