2

I know this question already exist in this forum, but every solution I founded not worked. I want to start an Activity from a non-Activity class. The non-Activity class is the DetailFragment.java of a Navigation-Drawer

DetaiFragment:

package com.developing.konstantin.besmart;

import android.annotation.TargetApi;
import android.app.Fragment;
import android.os.Build;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.FrameLayout;

@TargetApi(Build.VERSION_CODES.HONEYCOMB)
public class DetailFragment extends Fragment {

FrameLayout fLayout;

View view;

public DetailFragment() {
}

@Override
public View onCreateView(LayoutInflater inflater,ViewGroup container, Bundle args) {
    view = inflater.inflate(R.layout.menu_detail_fragment, container, false);
    String menu = getArguments().getString("Menu");

    switch (menu) {
        case ("Home"): {
            fLayout = (FrameLayout) view.findViewById(R.id.home) ;
            fLayout.setVisibility(View.VISIBLE);
            break;
        }

        case ("Info"): {
            fLayout = (FrameLayout) view.findViewById(R.id.info) ;
            fLayout.setVisibility(View.VISIBLE);
            break;
        }

        case ("Video"): {
            break;
        }
    }

    return view;
}
}

I want to start the Activity in the 3rd case ("Video"). How can I do that?

A.L
  • 10,259
  • 10
  • 67
  • 98
  • Welcome to Stack Overflow! Your English is fine :) You need to add a little more information, though. Why did the answers you found not work - it seems they all say you need to get a context and most suggest a way to do this e.g. http://stackoverflow.com/questions/6867084/how-to-retrieve-a-context-from-a-non-activity-class. EDIT: Don't worry - I see you have an answer now :) – J Richard Snape Jan 27 '15 at 17:13

2 Answers2

5

You can use the context :

inflater.getContext()

as:

startActivity(new Intent(inflater.getContext(), Video.class));

or you can use the getActivity() method like:

startActivity(new Intent(getActivity(), Video.class));
Jorgesys
  • 124,308
  • 23
  • 334
  • 268
0

It depends on from where you are calling the activity.

It is better to create an instance of

Context context;  

and initialize it like

context = AnyActivity.this; // if you are calling from Activity

context = getActivity(); // if you are using Fragments

And call it like

Intent intent = new Intent(context,ActivityToOpen.class);

startActivity(intent);
Zar E Ahmer
  • 33,936
  • 20
  • 234
  • 300