I have a MainActivity that handles the UIs and buttons, but I have a separate class that handles the onClickListener
portion of the code. My Main class is defined as: public class MainActivity extends Activity
and my buttons in the class are defined like:
MyButtonListener l = new MyButtonListener();
b1 = (Button) findViewById(R.id.button1);
b1.setOnClickListener(l);
The MyButtonListener
class is defined as public class MyButtonListener extends MainActivity implements View.OnClickListener
. The problem comes in, is when I try to make a toast in MyButtonListener
. I do not know what context to put for the toast. I have tried: MainActivity.this, MyButtonListener.this, getContextApplication(). None of them seemed to work. This is how I am trying to show my toast:
Toast.makeText(MyButtonListener.this, message, Toast.LENGTH_LONG).show();
Does anyone what context to put in order to show the toast from the MyButtonListener
class?
Create Global variable
Context context;
in MainActivity and set
context = this;
in onCreate Method of main activity
now pass the context in MyButtonListener Constructor like this
MyButtonListener l = new MyButtonListener(context);
b1 = (Button) findViewById(R.id.button1);
b1.setOnClickListener(l);
and in MyButtonListener add constructor
private Context context;
public MyButtonListener(Context context) {
this.context = context;
}
and use that context in toast
add a Context
to your MyButtonListener
's constructor and use it to show the Toast
.
public MyButtonListener(Context c);
from MainActivity
:
MyButtonListener l = new MyButtonListener(this);
Use View.getContext() from the parameters.
Eg:
...
void onClick(View v){
Context ctx = v.getContext();
}
...
This saves you from passing a context manually.
It is not the context you are getting but a different context of a different reference, instead you can pass the reference
of the main activity to your constructor of the MyButtonListener and use the context that was passed on it.
What you are doing is actually inheriting the mainactivity but not its reference by the time it is created so using the MyButtonListene.this
wont bring the toast on front . so extending mainactivity is completely useless/pointless.
I do not see any reason to have MyButtonListener extend MainActivity.
Do something like this:
public class MyButtonListener implements View.OnClickListener {
private Context context;
public MyButtonListener(Context context) {
this.context = context;
}
...
}
And pass the context from MainActivity:
MyButtonListener l = new MyButtonListener(this.getApplicationContext());
MyButtonListener l = new MyButtonListener(getApplicationContext());
and create parameterize constructor in
MyButtonListener
and use that Context
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.