Creating Intent in a New Method

So, I want the intention to launch an Activity, which simply brings up a popup with a dialog box telling the user how to use the application.

I have a 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 intent gives me an error:

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

Any idea on workarounds?

Thanks.

+4
source share
5 answers

The problem is that you are inside another class and passing Intent the wrong context. You must pass the correct context to it. 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; } } } 
+2
source

Edit

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

in

 Intent i = new Intent(TheCurrentClassName.this, About.class); 
+10
source

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

+1
source

A goal requires context. However, the use of this shortcut in the onClick function is not properly authorized. Different ways to provide the current context in an anonymous inner class - use Context.this instead. - Use getApplicationContext () instead. - Explicitly using the class name MenuScreen.this. Call a function declared at the desired context level.

+1
source

Just change

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

to

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

Hope this works.

+1
source

All Articles