【问题标题】:Toast: Difference between "this" and "getApplicationContext()"?Toast:“this”和“getApplicationContext()”之间的区别?
【发布时间】:2016-01-07 19:51:50
【问题描述】:

我的设备运行的是 Android 5.1.1,我发现如果我使用的话

Toast.makeText(this, "This is a toast", Toast.LENGTH_SHORT).show();

我知道了:

但如果我使用getApplicationContext() 而不是this

Toast.makeText(getApplicationContext(), "This is a toast", Toast.LENGTH_SHORT).show();

我知道了:

两者都直接从活动中调用。

这是为什么?

【问题讨论】:

    标签: android android-context android-toast android-5.1.1-lollipop


    【解决方案1】:

    它与上下文关联的主题有关。使用this 是使用与应用程序上下文具有不同主题的上下文(我假设您的ActivityFragment)。

    如果您有需要使用应用程序上下文的原因,您可以将其包装在您的活动使用的任何主题中(通常在您的AndroidManifest.xml 中设置),它应该显示“圆形”吐司。

    Toast.makeText(new ContextThemeWrapper(getApplicationContext(), R.style.AppTheme), "This is a toast", Toast.LENGTH_SHORT).show();
    

    【讨论】:

      猜你喜欢
      • 2012-05-25
      • 1970-01-01
      • 2013-10-23
      • 2012-08-18
      • 1970-01-01
      • 2017-12-22
      • 2012-03-15
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多