gpt4 book ai didi

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

转载 作者:IT老高 更新时间:2023-10-28 13:06:45 37 4
gpt4 key购买 nike

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

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

在我的 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"); }

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

为什么 foo 为空?

最佳答案

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

有道理,如果您不传递属性,例如 id,那么 View 将没有 id,因此无法使用该 id 找到。 :-)

关于xml - findViewById() 为布局 XML 中的自定义组件返回 null,而不是其他组件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1691569/

37 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com