[英]Starting new Activity not from the MainActivity file
I need to open new activity (using fragments if it's important) and I'm on a different file then the main activity so the code : 我需要打开新的活动(如果重要的话,请使用片段),并且我在与主要活动不同的文件中,因此代码如下:
Intent myIntent = new Intent(CurrentActivity.this, NextActivity.class);
CurrentActivity.this.startActivity(myIntent);
Is not good enough for me because I'm getting : 对我来说还不够好,因为我得到了:
...is not an enclosing class ERROR referring : CurrentActivity.this ...不是封闭类ERROR:CurrentActivity.this
Does someone knows how to solve it ? 有人知道如何解决吗?
Thanks... 谢谢...
You need to pass to Intent
constructor an instance of Context
class. 您需要将
Context
类的实例传递给Intent
构造函数。 So if you need to start new activity from Fragment
you shall write new Intent(getActivity(), NextActivity.class);
因此,如果需要从
Fragment
开始新活动,则应编写new Intent(getActivity(), NextActivity.class);
and start it like getActivity().startActivity(myIntent);
并像
getActivity().startActivity(myIntent);
一样启动它
If your are in a Class use this code: 如果您在班级中,请使用以下代码:
public class AnyClassName{
Context context;
public AnyClassName(Context context){
this.context = context;
}
public void AnyMethod(){
Intent myIntent = new Intent(context, NextActivity.class);
context.startActivity(myIntent);
}
}
If you are in Fragment then use this: 如果您在Fragment中,请使用以下命令:
public Class AnyFragmnet extends Fragment{
//all default methods which i am not declaring
public void AnyMethodName(){
Intent myIntent = new Intent(getActivity(), NextActivity.class);
getActivity().startActivity(myIntent);
}
}
there are some ways to solve this problem as I know. 据我所知,有一些方法可以解决此问题。 The main thing is you have to get a
context
object to start another activity. 最主要的是您必须获取一个
context
对象才能启动另一个活动。 Let's try one of below: 让我们尝试以下方法之一:
If you are using fragment
, try to call getActivity()
when start activity from fragment as: 如果您使用的是
fragment
,则在从fragment开始活动时,尝试调用getActivity()
,如下所示:
Intent i = new Intent(getActivity(), NextActivity.class); getActivity.startActivity(i);
Create an your Application class extends Application
for your project and then call getApplicationContext()
instead of call getActivity();
创建一个
Application class extends Application
为您的项目Application class extends Application
,然后调用getApplicationContext()
而不是调用getActivity();
Pass an Context
object to your fragment
and then use it instead of getActivity()
or getApplicationContext()
将
Context
对象传递给您的fragment
,然后使用它代替getActivity()
或getApplicationContext()
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.