Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Start a new Activity from Fragment

Using Android Studio, I have my MainActiviy class with a Placeholder fragment. This fragment has buttons, but one has to load an Activity. How does one do this? I was told to try something like the below, but the new Intent does not work.

Button button = (Button) rootView.findViewById(R.id.button1);
button.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
          Intent intent = new Intent(MainActivity.class, AnotherActivity.class);
          startActivity(intent);
        }
 });
like image 877
Stephanie Avatar asked Feb 19 '15 23:02

Stephanie


3 Answers

If you have a look at the documentation you can see that to start an activity you'll want to use the following code

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

Currently you're using MainActivity.class in a place that requires a context object. If you're currently in an activity, just passing this is enough. A fragment can get the activity via the getActivity() function.

Your full code above should look like this

Button button = (Button) rootView.findViewById(R.id.button1);
button.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View view) {
        Intent intent = new Intent(getActivity(), AnotherActivity.class);
        startActivity(intent);
    }
});
like image 126
Paul Thompson Avatar answered Oct 19 '22 19:10

Paul Thompson


You should use getActivity() to launch an Activity from Fragment.

From a Fragment: Context is parent activity (getActivity()).

Intent intent = new Intent(getActivity(), AnotherActivity.class);
startActivity(intent);
like image 26
Ferdous Ahamed Avatar answered Oct 19 '22 20:10

Ferdous Ahamed


If you have to use it inside onBindViewHolder, you may do this:

@Override
public void onClick(View view) {
    Intent intent= new Intent(view.getContext(), MainActivity.class);
    view.getContext().startActivity(intent);
}
like image 30
Nasser Ghodsian Avatar answered Oct 19 '22 20:10

Nasser Ghodsian