Toast.makeText(getApplicationContext(),"弦乐&QUOT ;, Toast.LENGTH_LONG); ==>此处getApplicationContext()不能更改到"本"? [英] Toast.makeText(getApplicationContext(), "String", Toast.LENGTH_LONG); ==>Here getApplicationContext() cannot change to "this"?

查看:397
本文介绍了Toast.makeText(getApplicationContext(),"弦乐&QUOT ;, Toast.LENGTH_LONG); ==>此处getApplicationContext()不能更改到"本"?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Toast.makeText()的第一格式为:

公共静态吐司makeText(上下文的背景下,CharSequence的文字,INT持续时间)
第一个参数是的上下文,功能 getApplicationContext()还返回当前的背景下,一切都很好,但海事组织, getApplicationContext()也可以用这个代替,就像如下:

 公共类ContextMenuResourcesActivity延伸活动{
    / **当第一次创建活动调用。 * /    私人按钮B1;    @覆盖
    公共无效的onCreate(捆绑savedInstanceState){
        super.onCreate(savedInstanceState);
        的setContentView(R.layout.main);
    B1 =(按钮)findViewById(R.id.button1);
    最终诠释L = Toast.LENGTH_LONG;
    最后弦乐S1 =一些字符串;
    b1.setOnClickListener(新OnClickListener(){
            公共无效的onClick(视图v){
                吐司T1 = Toast.makeText(这一点,S1,L);
                t1.show();
            }
        });
    }
}

IMO 这个 ContextMenuResourcesActivity ,它扩展了类上下文,所以它可以取代这对于要求第一个参数 上下文,但我失败了,任何人都可以解释为什么?


解决方案

当你创建一个实现特定接口的新 OnClickListener ,你正在创建一个匿名类。因此,这个不引用活动,因为你实际上是另一个对象。

下面是关于这个问题的匿名类VS代表 <一些更多的信息/ p>

First the format of Toast.makeText():

public static Toast makeText (Context context, CharSequence text, int duration) the first argument is Context, the function getApplicationContext() also return the current context, everything is ok, but IMO, the getApplicationContext() can also be replaced with this, just as follows:

public class ContextMenuResourcesActivity extends Activity {
    /** Called when the activity is first created. */

    private Button b1;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
    b1 = (Button)findViewById(R.id.button1);
    final int l = Toast.LENGTH_LONG;
    final String s1 = "some string";
    b1.setOnClickListener(new OnClickListener() {
            public void onClick(View v) {
                Toast t1 = Toast.makeText(this, s1, l);
                t1.show();
            }
        });
    }
}

IMO this stands for the class ContextMenuResourcesActivity, which extends Context, so it can replace the first argument which demands for Context, but I failed, can anyone explain why?

解决方案

When you create a new OnClickListener, you are creating a anonymous class which implements a particular interface. Thus, this does not refer to the Activity, since you are actually in another object.

Here's some more info on the subject Anonymous classes vs delegates

这篇关于Toast.makeText(getApplicationContext(),&QUOT;弦乐&QUOT ;, Toast.LENGTH_LONG); ==&gt;此处getApplicationContext()不能更改到&QUOT;本&QUOT;?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆