Re: [問題] view 與 class 的問題

作者: slemonade (淳)   2014-05-23 12:03:47
※ 引述《redok (火焰)》之銘言:
: 大家好
: 我將一個class (叫做Outter) extends 一個 TextView
: 然後在 MainActivity的 layout xml 中寫下了
: <View
: class="com.nextzero.testview.Outter"
: android:id="@+id/outter_layout"
: android:layout_height="wrap_content"
: android:layout_width="wrap_content"/>
: 然後Outter class 有覆寫 TextView原本的constructor (三個都有)
: public Outter(Context context, AttributeSet attrs, int defStyle) ...略
: 可是我在 MainActivity中,卻無法將我的View給取出
: Outter view = (Outter)findViewById( R.id.outter_layout);
: 這一行出現 ClassCastException ,可是我完全看不出來哪裡有問題...
: 可以請問為什麼嗎? 謝謝
: 附上完整程式碼link:
: https://dl.dropboxusercontent.com/u/110205128/TestView.zip
我又試了一下,你原本的方法是沒錯的,會錯誤是因為你的outter.class這個view的建構子有問題;你的建構子裡面有toast一個訊息,但是你少了一行初始化的動作:this.context=context;所以你的view的context=null,於是toast產生錯誤,錯誤是這樣產生的。只要將那行在toast之前補上去,你原本的寫法應該就能執行了。
作者: slemonade (淳)   2014-05-23 14:56:00
好像又有點不太對,不過把toast拿掉後是正常的,我說的不一定對,你參考試試哦
作者: redok (火焰)   2014-05-23 21:57:00
QQ謝謝大大 我找一下我看到的範例再貼連結找不太到|||

Links booklink

Contact Us: admin [ a t ] ucptt.com