2013-07-03 19 views
0

您好我想提出一個自定義視圖,並給予其他組件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" /> 

現在我想用這個TextView的在CustomView.java所以我在構造函數中做這在它的參考

int tId = a.getResourceId(R.styleable.CustomView_associatedTextView, 0); 
TextView tText = (TextView) findViewById(tId); 

但我發現tTextnull請告訴我我錯在哪裏或者我該怎麼做這樣的事情。請幫幫我。

+0

什麼錯'findViewById(R.id.text_view);'? – ozbek

+0

它也返回null –

回答

0

您的TextView不是您的自定義視圖的子項,這就是爲什麼findViewById無法找到它。

呼叫findViewById從根視圖,自定義視圖已經被附後:

protected void onAttachedToWindow() { 
    super.onAttachedToWindow(); 
    int tId = a.getResourceId(R.styleable.CustomView_associatedTextView, 0); 
    TextView tText = (TextView) getRootView().findViewById(tId); 
} 
相關問題