您好我正在制作一个自定义视图,并在其中提供其他组件ID作为参考
<com.example.timerview.CustomView
android:id="@+id/custom_view"
android:layout_width="100dip"
android:layout_height="100dip"
mtv:associatedTextView="@+id/text_view"
/>
<TextView
android:id="@+id/text_view"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
现在我想在CustomView.java中使用这个TextView,所以我在构造函数
中这样做int tId = a.getResourceId(R.styleable.CustomView_associatedTextView, 0);
TextView tText = (TextView) findViewById(tId);
但我发现tText
是null
请告诉我我错在哪里或我该怎么办呢。请帮帮我。
答案 0 :(得分:0)
您的TextView不是自定义视图的子代,这就是findViewById
无法找到它的原因。
在附加自定义视图后,从根视图中调用findViewById
:
protected void onAttachedToWindow() {
super.onAttachedToWindow();
int tId = a.getResourceId(R.styleable.CustomView_associatedTextView, 0);
TextView tText = (TextView) getRootView().findViewById(tId);
}