findViewByID 返回 null [英] findViewByID returns null

查看:33
本文介绍了findViewByID 返回 null的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

首先:是的,我阅读了有关此主题的所有其他主题.不仅仅是来自这个网站的那些...(你看,我有点沮丧)

First of all: yes, I read all the other threads on this topic. And not only those from this site... (you see, I'm a little frustrated)

他们中的大多数人都建议在 XML 文件中使用 android:id 而不是 id.我做到了.

Most of them come with the advice to use android:id instead of just id in the XML file. I did.

我从其他人那里了解到,View.findViewByIdActivity.findViewById 的工作方式不同.我也处理过.

From others, I learned, that View.findViewById works different than Activity.findViewById. I handled that, too.

在我的 location_layout.xml 中,我使用:

In my location_layout.xml, I use:

<FrameLayout .... >
    <some.package.MyCustomView ... />

    <LinearLayout ... >
        <TextView ...
            android:id="@+id/txtLat" />
        ...
    </LinearLayout>
</FrameLayout>

在我的活动中:

...
setContentView( R.layout.location_layout );

在我的自定义视图类中:

and in my custom view class:

... 
TextView tv = (TextView) findViewById( R.id.txtLat );

返回 null.这样做,我的 Activity 工作正常. 所以可能是因为 Activity.findViewByIdView.findViewById 的差异.所以我在本地存储了传递给海关视图构造函数的上下文并尝试:

which returns null. Doing this, my Activity works fine. So maybe it's because of the Activity.findViewById and View.findViewById differences. So I stored the context passed to the customs view constructor locally and tried:

...
TextView tv = (TextView) ((Activity) context).findViewById( R.id.txtLat );

也返回了 null.

然后,我更改了自定义视图以扩展 ViewGroup 而不是 View 并更改了 location_layout.xml 以让 TextView 是我的自定义视图的直接子级,以便 View.findViewById 应该按预期工作.惊喜:它没有解决任何问题.

Then, I changed my custom view to extend ViewGroup instead View and changed the location_layout.xml to let the TextView be a direct child of my custom view, so that the View.findViewById should work as supposed. Suprise: it didn't solve anything.

那我到底做错了什么?

我将不胜感激任何评论.

I'll appreciate any comments.

推荐答案

返回空

可能是因为你打电话太早了.等到 onFinishInflate().这是一个示例项目,演示了自定义View 访问其内容.

Possibly because you are calling it too early. Wait until onFinishInflate(). Here is a sample project demonstrating a custom View accessing its contents.

这篇关于findViewByID 返回 null的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆