使用ApplicationContext渲染布局引发的问题
上下文描述
在一个ListView
的Adapter
里边,我用LayoutInflator
渲染一个布局,在item
布局中,我想加一个点击效果,所以就有了这样一段代码:
<LinearLayout
android:id="@+id/ll_click_view"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="?attr/selectableItemBackground"
android:gravity="center_vertical"
android:orientation="horizontal">
......
使用android:background="?attr/selectableItemBackground"
可以为布局增加点击效果,会根据系统变化的。
问题出现
当我在打开APP时,出现了崩溃,崩溃信息是 android:background="?attr/selectableItemBackground"
这一行渲染不了。
问题排查
当时我想,?attr
属于是根据主题去找寻,哪里可能导致出现这个问题呢,想到我的LayoutInflator
创建过程。
// MyApplication.context是保存的Application的Context
LayoutInflater inflater = LayoutInflater.from(MyApplication.context);
推断:Application
的Context
找不到主题相关的信息,所以?attr
解析不了,导致出现了错误。
所以果断使用Activity
的Context
当做参数传递给LayoutInflater
,果然点击效果出现了,而且没再崩溃。
总结
Application
的Context
虽然有时候很方便一些操作,但是也具有局限性,比如不能当做Dialog
的参数传递,当然还有一系列其他的不能做的事情,查看官网吧!
附录Conext
各种限制(来源于网络,不保证准确性)
Application | Activity | Service | ContentProvider | Broadcast | |
---|---|---|---|---|---|
Show Dialog | X | √ | X | X | X |
Start an Activity | X¹ | √ | X¹ | X¹ | X¹ |
Layout inflation | X² | √ | X² | X² | X² |
Start a Service | √ | √ | √ | √ | √ |
Bind to Service | √ | √ | √ | √ | X |
Send a BroadCast | √ | √ | √ | √ | √ |
Register Broadcast Receiver | √ | √ | √ | √ | X³ |
Load Resource Values | √ | √ | √ | √ | √ |
说明:
X¹ : 启动Activity在这些类中是可以的,但是需要创建一个新的task。一般情况不推荐
X² : 在这些类中去layout inflate是合法的,但是会使用系统默认的主题样式,如果你自定义了某些样式可能不会被使用。
X³ : 在receiver为null时允许,在4.2或以上的版本中,用于获取黏性广播的当前值。(可以无视)