【问题标题】:Why is my toast working with so many different contexts?为什么我的 toast 可以在这么多不同的环境下工作?
【发布时间】:2019-01-09 08:44:57
【问题描述】:

我在我的activity4.java中工作,代码是:

public class Activity4 extends Activity {
Spinner spinner;
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_4);
    spinner=findViewById(R.id.spinner);

    spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
        @Override
        public void onItemSelected(AdapterView<?> adapterView, View view, int i, long l) {
            if(Activity4.this==adapterView.getContext())
            Toast.makeText(adapterView.getContext(),adapterView.getSelectedItem().toString(),Toast.LENGTH_LONG).show();
        }

        @Override
        public void onNothingSelected(AdapterView<?> adapterView) {

        }
    });
}
}

我在上面的代码中使用了 adapterView.getContext() 作为上下文。但即使我用 getApplicationContext() 替换它

Toast.makeText(getApplicationContext(),adapterView.getSelectedItem().toString(),Toast.LENGTH_LONG).show();

或者如果我这样写 getBaseContext(),

Toast.makeText(getBaseContext(),adapterView.getSelectedItem().toString(),Toast.LENGTH_LONG).show();

吐司似乎很好用。为什么会这样?

【问题讨论】:

  • 为什么要使用adapterView.getContext()?你会做 MainActivity.this

标签: android


【解决方案1】:

这是Toast.java中makeText()方法的实现:

/**
 * Make a standard toast that just contains a text view.
 *
 * @param context  The context to use.  Usually your {@link android.app.Application}
 *                 or {@link android.app.Activity} object.
 * @param text     The text to show.  Can be formatted text.
 * @param duration How long to display the message.  Either {@link #LENGTH_SHORT} or
 *                 {@link #LENGTH_LONG}
 *
 */
public static Toast makeText(Context context, CharSequence text, @Duration int duration) {
    return makeText(context, null, text, duration);
}

正如您在 @param context 的 cmets 中看到的那样,它通常是应用程序的上下文或活动的上下文。

但是文档:

这个方法接受三个参数:应用上下文、文本 消息,以及 toast 的持续时间

声明上下文必须是应用程序上下文。

好吧,Toast 似乎只需要一个上下文。
如果可能,我们必须使用应用程序上下文来避免意外结果。
虽然我还没有看到。

【讨论】:

  • 这可能不是最好的重载演示,因为它只调用另一种形式的 makeText。在实际实现中,它是“LayoutInflater inflate = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);”。这就是为什么它需要 context.to 膨胀“com.android.internal.R.layout.transient_notification”
  • @Elletlar 也许是最常用的
猜你喜欢
  • 1970-01-01
  • 2022-08-15
  • 2022-07-21
  • 2011-07-20
  • 1970-01-01
  • 1970-01-01
  • 2023-01-28
  • 2019-11-20
  • 1970-01-01
相关资源
最近更新 更多