试图从非可视上下文访问 UI 常量

问题描述

我在 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

错误是在扩展 getViewImageAdapter 类的 BaseAdapter 方法中触发的:

    ....
    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 上下文有误?哪个是正确的?

解决方法

哪个是正确的?

您的 Activity 是正确的 Context。理想情况下,在您的 getLayoutInflater() 上调用 Activity 并使用它。