简体   繁体   中英

Best practice to have a button in fragment that triggers intent to another activity Java android studio

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM