Android : Calling Activity from Fragment

爱⌒轻易说出口 提交于 2019-11-27 12:30:58
Chinmoy Debnath

Get the parent activity using get activity then do as usual.

Intent myIntent = new Intent(getActivity(), BookmarkActivity.class);
getActivity().startActivity(myIntent); 

Here is another alternative method. This worked for me.

public class **YourFragmentClass** extends Fragment {

    Context context; //Declare the variable context

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

    //Pass your layout xml to the inflater and assign it to rootView.
      View rootView = inflater.inflate(R.layout.**yourfragmentxml**, container, false); 
            context = rootView.getContext(); // Assign your rootView to context

            Button **yourButton** = (Button) rootView.findViewById(R.id.**your_button_id**);
            **yourButton**.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    //Pass the context and the Activity class you need to open from the Fragment Class, to the Intent
                    Intent intent = new Intent(context, **YourActivityClass**.class); 
                    startActivity(intent);
                }
            });
            return rootView;
        }
    }
SubbaReddy PolamReddy

To call another activity from fragment use this:

Intent i = new Intent(getActivity(), Activity.class);
startActivity(i);
Divyesh V.Murani

In Fragment Class

 getActivity().startActivity(new Intent(gwtActivity(),MainActivity.class));
 getActivity().finish();
Ashok Reddy M

Your fragment should have a parent

Intent intent = new Intent(getActivity(), SecondActivity.class);
getActivity().startActivity(intent);  

Best way of calling Activity from Fragment class is that make interface in Fragment and add onItemClick() method in that interface. Now implement it to your first activity and call second activity from there.

You can simply call

startActivity(new Intent(getActivity(),TheNextActivity.class));
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!