findViewByID返回null [英] findViewByID returns null

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

问题描述

首先:是的,我读了所有关于这一主题的其他线程。而不仅仅是从本网站...(你看,我有点沮丧)

他们中的大多数都与建议使用机器人:ID ,而不是仅仅 XML文件中的id 。我做到了。

这是别人,我才知道,那 View.findViewById 作品比 Activity.findViewById 不同。我处理这一点。

在我的 location_layout.xml ,我用:

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

    < LinearLayout中...>
        < TextView中...
            机器人:ID =@ + ID / txtLat/>
        ...
    < / LinearLayout中>
< /的FrameLayout>
 

在我的活动我做的:

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

和我的自定义视图类:

  ...
TextView的电视=(TextView中)findViewById(R.id.txtLat);
 

返回这样做,我的活动能正常工作。所以,也许这是因为 Activity.findViewById View.findViewById 的差异。所以,我存储传递给海关的背景下查看当地的构造,并试图:

  ...
TextView的电视=(TextView中)((活动)范围内).findViewById(R.id.txtLat);
 

这也返回

于是,我改变了我的自定义视图扩展的ViewGroup ,而不是查看,改变了 location_layout.xml 的TextView 是我的自定义视图的直接子,使 View.findViewById 应该像预想的那样。惊喜:它并没有解决任何问题。

那么,到底我做错了什么?

我会AP preciate任何意见。

解决方案
  

这将返回null

可能是因为你太早期调用它。等到 onFinishInflate()这里是展示一个自定义的一个示例项目查看访问其内容。

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)

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

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

In my location_layout.xml, I use:

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

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

In my Activity I do:

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

and in my custom view class:

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

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 );

which also returned null.

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.

So what the heck am I doing wrong?

I'll appreciate any comments.

解决方案

which returns null

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天全站免登陆