Java 显示onClickListener类中Toast的上下文
我有一个MainActivity来处理UI和按钮,但我有一个单独的类来处理代码的Java 显示onClickListener类中Toast的上下文,java,android,Java,Android,我有一个MainActivity来处理UI和按钮,但我有一个单独的类来处理代码的onClickListener部分。我的主类定义为:public class MainActivity extends Activity,类中的我的按钮定义如下: MyButtonListener l = new MyButtonListener(); b1 = (Button) findViewById(R.id.button1); b1.setOnClickListener(l); MyButtonListen
onClickListener
部分。我的主类定义为:public class MainActivity extends Activity
,类中的我的按钮定义如下:
MyButtonListener l = new MyButtonListener();
b1 = (Button) findViewById(R.id.button1);
b1.setOnClickListener(l);
MyButtonListener
类被定义为公共类MyButtonListener扩展了MainActivity implements View.OnClickListener
。问题是,当我试图在MyButtonListener
中祝酒时。我不知道祝酒词的上下文是什么。我尝试过:MainActivity.this、MyButtonListener.this、getContextApplication()。它们似乎都不起作用。这就是我想表达我的祝酒词的方式:
Toast.makeText(MyButtonListener.this, message, Toast.LENGTH_LONG).show();
是否有人为了显示
MyButtonListener
类中的toast而放置了什么上下文?将上下文添加到MyButtonListener
的构造函数中,并使用它来显示toast
public MyButtonListener(Context c);
从main活动
:
MyButtonListener l = new MyButtonListener(this);
您获得的不是上下文,而是不同引用的不同上下文,相反,您可以将主要活动的引用
传递给MyButtonListener的构造函数,并使用传递给它的上下文
您所做的实际上是继承mainactivity,但在创建mainactivity时不继承它的引用,因此使用MyButtonListene。这不会让toast出现在前面。因此,扩展mainactivity是完全无用/毫无意义的。创建全局变量
Context context;
在活动和设置中
context = this;
主活动的一次创建方法
现在在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;
}
在toast中使用该上下文我看不出有任何理由让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());
使用参数中的View.getContext()
例如:
这样可以避免手动传递上下文
MyButtonListener l = new MyButtonListener(getApplicationContext());
and create parameterize constructor in
MyButtonListener
and use that Context
MyButtonListener l = new MyButtonListener(getApplicationContext());
and create parameterize constructor in
MyButtonListener
and use that Context