Creating an intent in a new method

2019-02-14 15:26发布

So I want an intent to start an Activity that simply brings up a dialog popup box telling the user how to use the app.

I have the code:

private final View.OnClickListener btnClick = new View.OnClickListener() {
    @Override
    public void onClick(View v) {
        switch (v.getId()) {
        case R.id.about_box:
            Intent i = new Intent(this, About.class);
            startActivity(i);
            break;
        }
    }
}

but the Intent is giving me the error:

The constructor Intent(new View.OnClickListener(){}, Class) is undefined

Any idea on workarounds?

Thanks.

5条回答
Luminary・发光体
2楼-- · 2019-02-14 15:50

Change,

Intent i = new Intent(this, About.class);

to,

Intent i = new Intent(TheCurrentClassName.this, About.class);
查看更多
▲ chillily
3楼-- · 2019-02-14 15:53

The intent needs a context. However, using the this shortcut in the onClick function is not properly resolved. Different ways to provide current context in an anonymous inner class are - Use Context.this instead of this. - Use getApplicationContext() instead of this. - Explicitly use the class name MenuScreen.this. Call a function that is declared at the right context level.

查看更多
等我变得足够好
4楼-- · 2019-02-14 15:53

Just change

Intent i = new Intent(this, About.class);

to

Intent i = new Intent(Classname.this, About.class);

Hope it works.

查看更多
啃猪蹄的小仙女
5楼-- · 2019-02-14 16:06

Change the intent line to: Intent intent = new Intent(ClassName.this, theNewClassName.class);

查看更多
够拽才男人
6楼-- · 2019-02-14 16:08

The problem is that you are inside another class there and are passing the Intent a wrong context. You have to pass it the right context. Take a look at the example below.

// your Activity

public class MyActivity extends Activity {

    Context ctx = null;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        ctx = getApplication();
    }

    private final View.OnClickListener btnClick = new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            switch (v.getId()) {
            case R.id.about_box:

                Intent i = new Intent(ctx, About.class);
                startActivity(i);
                break;
            }
        }
    }
查看更多
登录 后发表回答