findViewById()为布局XML中的自定义组件返回null,而不是其他组件

Chr*_*yle 90 xml layout android

我有一个res/layout/main.xml包括这些元素和其他:

<some.package.MyCustomView android:id="@+id/foo" (some other params) />
<TextView android:id="@+id/boring" (some other params) />
Run Code Online (Sandbox Code Playgroud)

在我的Activity的onCreate中,我这样做:

setContentView(R.layout.main);
TextView boring = (TextView) findViewById(R.id.boring);
// ...find other elements...
MyCustomView foo = (MyCustomView) findViewById(R.id.foo);
if (foo == null) { Log.d(TAG, "epic fail"); }
Run Code Online (Sandbox Code Playgroud)

其他元素成功找到,但foo返回null.MyCustomView有一个构造函数,MyCustomView(Context c, AttributeSet a)并且Log.d(...)该构造函数的末尾在"史诗失败"之前的logcat中成功出现.

为什么是foonull?

Chr*_*yle 176

因为在构造函数中,我有super(context)而不是super(context, attrs).

有道理,如果你没有传递属性,比如id,那么视图将没有id,因此无法使用该id找到.:-)

  • 另外,你不应该像`(MyCustomView)foo = findViewById(R.id.foo);```MyCustomView foo =(MyCustomView)findViewById(R.id.foo);`? (4认同)
  • 有同样的问题,在我的情况下,我忘记了setContentView().. XD (3认同)

Ale*_*huk 25

我有同样的问题,因为在我的自定义视图中我覆盖了构造函数,但调用了超级构造函数withot attrs paramete.那是复制粘贴)

我以前的构造函数版本:

    public TabsAndFilterRelativeLayout(Context context, AttributeSet attrs) {
            super(context);
}
Run Code Online (Sandbox Code Playgroud)

我现在有:

    public TabsAndFilterRelativeLayout(Context context, AttributeSet attrs) {
            super(context, attrs);}
Run Code Online (Sandbox Code Playgroud)

这有效!


Vin*_*ent 18

我有同样的问题.我的错误在于:我写道

        LayoutInflater inflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        View layout=inflater.inflate(R.layout.dlg_show_info, null);
        alertDlgShowInfo.setView(layout);
        TableRow trowDesc=(TableRow)findViewById(R.id.trowDesc);
Run Code Online (Sandbox Code Playgroud)

当我使用inflater从XML文件"加载"视图时,最后一行是错误的.要解决它,我不得不写:

TableRow trowDesc=(TableRow)layout.findViewById(R.id.trowDesc);
Run Code Online (Sandbox Code Playgroud)

我写了我的解决方案,以防有人遇到同样的问题.


jel*_*ish 18

似乎有多种原因.我只是在Eclipse中使用"Clean ..."来解决类似的问题.(FindViewByID之前已经工作过,并且由于某种原因开始返回null.)


Dan*_*iel 11

同样的问题,但不同的解决方案:我没有打电话

setContentView(R.layout.main)
Run Code Online (Sandbox Code Playgroud)

在我试图找到这里所说的观点之前