Home > database >  Best practice to have a button in fragment that triggers intent to another activity Java android stu
Best practice to have a button in fragment that triggers intent to another activity Java android stu

Time:01-20

In iOS Swift coding, if a cell(like a fragment?) has button that triggers a transition from controller A to controller B (intent activity), I use delegate to pass the data from the cell (fragment) to the controller A (activity), then I write intent at controller A.

In Java, for example, I have a button in a fragment:

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {
    View v = inflater.inflate(R.layout.fragment_profile, container, false);

    AppCompatButton button = (AppCompatButton) v.findViewById(R.id.buyercenterid);

    button(new View.OnClickListener() {
        public void onClick(View v) {
           // something like delete to pass data to Activity then write intent in activity?
        }
    });
    return v;
}

I know I need to write an interface to connect the fragment and the activity. However, I can't find a workable solution to do it properly.

CodePudding user response:

You can call getActivity() and cast to an interface that your activity implements.

This interface is a contract between the activity and the fragment. Then the fragment just needs to call the interface method, which is implemented in the activity.

Example: https://stackoverflow.com/a/65117569

  • Related