[英]Context to show Toast from onClickListener class
我有一个MainActivity来处理UI和按钮,但我有一个单独的类来处理代码的onClickListener
部分。 我的Main类定义为: public class MainActivity extends Activity
,类中的按钮定义如下:
MyButtonListener l = new MyButtonListener();
b1 = (Button) findViewById(R.id.button1);
b1.setOnClickListener(l);
MyButtonListener
类定义为public class MyButtonListener extends MainActivity implements View.OnClickListener
。 问题来自于,当我尝试在MyButtonListener
举杯时。 我不知道吐司的背景。 我尝试过:MainActivity.this,MyButtonListener.this,getContextApplication()。 他们似乎都没有工作。 这就是我试图展示吐司的方式:
Toast.makeText(MyButtonListener.this, message, Toast.LENGTH_LONG).show();
有没有人为了从MyButtonListener
类中显示toast而放置什么上下文?
创建全局变量
Context context;
在MainActivity和Set中
context = this;
in onCreate主要活动方法
现在像这样在MyButtonListener构造函数中传递上下文
MyButtonListener l = new MyButtonListener(context);
b1 = (Button) findViewById(R.id.button1);
b1.setOnClickListener(l);
并在MyButtonListener中添加构造函数
private Context context;
public MyButtonListener(Context context) {
this.context = context;
}
并在吐司中使用该上下文
将一个Context
添加到MyButtonListener
的构造函数中,并使用它来显示Toast
。
public MyButtonListener(Context c);
来自MainActivity
:
MyButtonListener l = new MyButtonListener(this);
从参数中使用View.getContext()。
例如:
...
void onClick(View v){
Context ctx = v.getContext();
}
...
这样可以避免手动传递上下文。
它不是您获得的上下文,而是不同引用的不同上下文,而是您可以pass the reference
主活动pass the reference
给MyButtonListener的构造函数 ,并使用在其上传递的上下文。
你正在做的事实上是继承mainactivity而不是它的创建时间,所以使用MyButtonListene.this
不会在前面带来吐司。 所以扩展主要活动是完全没用的/没有意义的。
我没有看到任何理由让MyButtonListener扩展MainActivity。
做这样的事情:
public class MyButtonListener implements View.OnClickListener {
private Context context;
public MyButtonListener(Context context) {
this.context = context;
}
...
}
并从MainActivity传递上下文:
MyButtonListener l = new MyButtonListener(this.getApplicationContext());
MyButtonListener l = new MyButtonListener(getApplicationContext());
and create parameterize constructor in
MyButtonListener
and use that Context
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.