'How can I send data from a tablayout fragment to the main activity

I have a listview in my tablayout. When I click on one of these elements, I want that element to be added to a list in the mainactivity. So that I can display this list on another fragment.



Solution 1:[1]

You can use interface when clicked on item Create interface like this in one fragment

public interface OnClickListener{
     void onClick(Item listItem);
}

and in fragment create object like:

OnClickListener onClickListener;

and in onAttach assign the object

 @Override
 public void onAttach(Context context) {
super.onAttach(context);
    try {
      onClickListener= (onClickListener) context;
    } catch (ClassCastException e) {
       
    }
 }

and then implement this listener in your MainActivity

public class MainActivity extends AppCompatActivity implements onClickListener{}

and on button click in fragment pass the data to your MainActivity

 button.setOnClickListener(new OnClickListener() {
  public void onClick(View v) {
    onClickListener.onClick(YOUR_ITEM);
  }
});

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 shah