Reputation: 933
I have a class file MainActivity and i want switch to Testing.class file. So this is following code.
public static class MyFragment extends Fragment
{
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState)
{
View rootView = inflater.inflate(R.layout.xyz, container, false);
final TextView tt=(TextView) rootView.findViewById(R.id.txt);
Button button=(Button) rootView.findViewById(R.id.btn1);
View.OnClickListener sx = new OnClickListener()
{
public void onClick(View v)
{
call();
}
};
button.setOnClickListener(sx);
return rootView;
}
private void call()
{
// Here getting the Error //
Intent intent = new Intent(MainActivity.this, Testing.class);
startActivity(intent);
}
}
So, this is the above code , i want to switch to new class file called Testing but
i am facing an error-: No enclosing instance of the type MainActivity is accessible in scope
I think creating an new static class called MyFragment within MainActivity creating problem.
So, please help me out and give me some good solution.
Upvotes: 0
Views: 38
Reputation: 2185
You can use getActivity()
method inside your fragment but take care that this method might return null in case of calling it before getting onActivityCreated()
method
Upvotes: 0
Reputation: 612
Okay so you cannot call MainActivity.this since you are in the fragment class. You have to access the context in a different way. Such as
getActivity()
which returns the activity associated with the fragment. The activity is a context (Since Activity extends Context)
Upvotes: 1