美文网首页
Toast文字不居中

Toast文字不居中

作者: nianyounan | 来源:发表于2017-03-09 16:48 被阅读116次

    当你在API19以上定义沉浸式风格的UI时,可能会定义整个App的Theme为:

            <item name="android:windowTranslucentNavigation">true</item>
            <item name="android:windowTranslucentStatus">true</item>
            <item name="android:fitsSystemWindows">true</item>
    

    这样的话Toast的文字便不会居中显示,而在背景框中靠上的位置。

    随手搜一下,会得到如下答案:

    • 将fitsSystemWindows设置为false。
      (WTF,我要是能设置成false就不在AppTheme中指定为true了。)
    • 将Toast.makeText(context, msg, length)中第一个参数的context使用Application的Context而不是使用Activity的context。
      (结果是居中了,可是Toast的样式却也变了。)

    解决方案

    问题的原因在于将fitsSystemWindows用错了地方。fitsSystemWindows应该定义在View的Layout文件中,而不是定义在Theme里。

    The android:fitsSystemWindows attribute is intended for usage on views in layout xml, not in themes.
    What you're seeing is the effect of the way the styled attribute system works in Android. If no attribute is specified on the view element or in the explicit style given to the view, the framework checks to see if that attribute has been specified on the theme itself. If it is found there, that value is used. Since the views used by toasts use your activity's theme, the default value of false is overridden and you see this behavior.
    You're not just changing the fitsSystemWindows default for your top-level views by specifying it in the theme, you're overriding it for all views with that theme, which isn't what you want. You should only specify fitsSystemWindows on views within your layouts or in styles that you explicitly apply to views within your layouts, not on themes.

    参考:
    AOSP Issue 63653 - 科学上网

    相关文章

      网友评论

          本文标题:Toast文字不居中

          本文链接:https://www.haomeiwen.com/subject/yztggttx.html