Mar 20, 2021

How to open another activity click on button in fragment android studio - Androidpro.in

 Okay so I've tried two types of code to get this to work and it keeps giving me force closes when I press the button to go into another Activity. I'm using a Fragment and there's a button in that Fragments code but I can't seem to get it to work.


1st Method


public class About extends Fragment {

    Intent intent;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {

        View rootView = inflater.inflate(R.layout.about, container, false);

        intent = new Intent(getActivity(), Contact_Developer.class);
        final Button button = (Button) rootView.findViewById(R.id.btnContactDev);

        button.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {
                startActivity(intent);
            }
        });

        return rootView;
    }
}


2nd Method

public class About extends Fragment {

    public void onCreate (Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {

        View rootView = inflater.inflate(R.layout.about, container, false);

        Button button = (Button) rootView.findViewById(R.id.btnContactDev);
        button.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View arg0) {
                Intent intent = new Intent(getActivity(), Contact_Developer.class);
                getActivity().startActivity(intent);
            }
        });
        return rootView;
    }
}



Whatsapp Button works on Mobile Device only