findViewById() from custom view return null
似乎与其他问题相似,但我没有找到解决方案。 我有一个由xml文件定义的布局:
main_layout.xml
1 2 3 4 5 6 7 8 9 10 11 12 13 | <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" ... > <package.CustomView ... > </package.CustomView> <TextView android:id="@+id/text_view" ... > </TextView> </RelativeLayout> |
CustomView扩展SurfaceView的位置。
在onCreate中,我有setContentView(R.layout.main_layout)。 现在,例如,如果要充气,必须在setContentView(...)之后添加的活动中添加TextView
1 | TextView textView = (TextView) findViewbyId(R.id.text_view); |
一切正常。 但是,如果我将此行放入CustomView的方法中,则会得到一个空指针。 为什么?
在活动中,开始遍历
理解上面的有用解释后,我想提供一种简单的方法来通过
1 | (Activity)getContext()).findViewById(R.id.youViewToBeFound); |
在您的
此代码必须在构造函数代码之后运行,例如 内部