Android Intent Cannot resolve constructor

2019-01-13 07:37发布

I have a first class extending Fragment, and a second class extending Activity.

My Fragment is working fine, and my code for the Intent in the Fragment is :

ImageButton button= (ImageButton) getView().findViewById(R.id.button);
    button.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            Intent myIntent = new Intent(MyFragment.this, MyClass.class);
            MyFragment.this.startActivity(myIntent);            }
    });

My class MyClass code is :

public class MyClass extends Activity {
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        // The activity is being created.
    }

    @Override
    protected void onStart() {
        super.onStart();

        setContentView(R.layout.MyClass);
    } 
}

The error is :

Gradle: cannot find symbol constructor Intent(com.xxxx.xxxx.MyFragment,java.lang.Class<com.xxxx.xxxx.MyClass>)

I don't know where I went wrong.

5条回答
贼婆χ
2楼-- · 2019-01-13 08:01

You Can not Use the Intent's Context for Creating Intent. So You need to use your Fragment's Parent Activity Context

Intent intent = new Intent(getActivity(),MyClass.class);
查看更多
可以哭但决不认输i
3楼-- · 2019-01-13 08:07

Or you can simply start the activity as shown below;

startActivity( new Intent(currentactivity.this, Tostartactivity.class));
查看更多
放我归山
4楼-- · 2019-01-13 08:07

You may use this:

Intent intent = new Intent(getApplicationContext(), ClassName.class);
查看更多
小情绪 Triste *
5楼-- · 2019-01-13 08:08

Use

Intent myIntent = new Intent(v.getContext(), MyClass.class);

or

 Intent myIntent = new Intent(MyFragment.this.getActivity(), MyClass.class);

to start a new Activity. This is because you will need to pass Application or component context as a first parameter to the Intent Constructor when you are creating an Intent for a specific component of your application.

查看更多
走好不送
6楼-- · 2019-01-13 08:08

Using .getActivity() solves this issue:

For eg.

Intent i= new Intent(MainActivity.this.getActivity(), Next.class);
startActivity(i);

Hope this helps.

Cheers.

查看更多
登录 后发表回答