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

3

我正在使用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

这个错误是在扩展了BaseAdapterImageAdapter类的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使用了错误的上下文?正确的上下文是哪个?

1个回答

2

哪一个是正确的?

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


太棒了!我刚刚通过将ImageAdapter()更改为ImageAdapter(Context context),并使用new ImageAdapter(this)创建了实例,而不是new ImageAdapter()。错误消失了。谢谢! - Luis A. Florit
对于包括在XML文件中定义的View类,我们应该怎么做呢?对于那些被填充的View类,提供构造函数中的上下文。但即使有了这个上下文,它仍然抛出相同类型的错误。 - jettimadhuChowdary
@jettimadhuChowdary:在View上调用getContext()应该会给你一个合适的Context。如果没有,你可能想要提出一个单独的Stack Overflow问题,附上一个[mcve],展示你如何填充布局,并提供你所见到的具体错误的细节。 - CommonsWare

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接