我正在使用StrictMode运行我的图像查看器应用程序,以尝试捕获内存泄漏。在显示许多缩略图的活动中,我看到了几次错误(可能是每个缩略图一次):
E/ViewConfiguration: Tried to access UI constants from a non-visual Context:android.app.Application@7f56ef7UI constants, such as display metrics or window metrics, must be accessed from Activity or other visual Context. Use an Activity or a Context created with Context#createWindowContext(int, Bundle), which are adjusted to the configuration and visual bounds of an area on screen
java.lang.IllegalArgumentException: Tried to access UI constants from a non-visual Context:android.app.Application@7f56ef7
这个错误是在扩展了BaseAdapter
的ImageAdapter
类的getView
方法中触发的:
....
public View getView(int pos, View convertView, ViewGroup parent) {
ViewHolder holder;
if (convertView == null) {
convertView = inflater.inflate(R.layout.thumbitem, parent, false);
...
这一行 convertView = inflater.inflate...
是导致错误的代码。
该类还有以下方法,也会触发一个 Tried to access visual service LayoutInflater from a non-visual Context
错误:
ImageAdapter() {
inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
看起来我的inflater
使用了错误的上下文?正确的上下文是哪个?
ImageAdapter()
更改为ImageAdapter(Context context)
,并使用new ImageAdapter(this)
创建了实例,而不是new ImageAdapter()
。错误消失了。谢谢! - Luis A. FloritView
上调用getContext()
应该会给你一个合适的Context
。如果没有,你可能想要提出一个单独的Stack Overflow问题,附上一个[mcve],展示你如何填充布局,并提供你所见到的具体错误的细节。 - CommonsWare