如何在自定义视图中获取作为参考的组件?

时间:2013-07-03 12:10:20

标签: android custom-component

您好我正在制作一个自定义视图,并在其中提供其他组件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);

但我发现tTextnull请告诉我我错在哪里或我该怎么办呢。请帮帮我。

1 个答案:

答案 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);
}