android關於用.xml佈局檔案中對View新增OnClick事件無法響應的事情
阿新 • • 發佈:2019-02-15
最近在寫一個專案,用到了Fragment,於是在Fragment裡用用LayoutInflate映射了一個.xml的佈局檔案,
mRootView = (ViewGroup) inflater.inflate(R.layout.luka_category_fragment, null, false);在luka_category_fragment中有一個TextView
<span style="font-size:18px;"><TextView android:id="@+id/testBtn" android:layout_width="match_parent" android:layout_height="40dp" android:background="@color/red" android:onClick="test" /></span>
我在這個Fragment裡實現了這個public void test(View view){system.out.println("test")}可發現並沒有效果,點選沒有任何反應,就是xml的onClick沒有起作用。後來我把佈局裡的TextView改成了Button,點選有了效果,可是一點就奔潰了,說是沒有實現這個test方法。我想了想我再Fragment裡實現了啊,卻沒有走。後來我想了想這個應該是在Fragment對應的Activity中去實現這個test方法。像上面如果你的View為TextView或其它的非Button的View在xml裡設定事件是沒有效果的。
我發現自己自定義的一個View,裡面映射了一個佈局檔案,佈局檔案裡設定事件也是沒效果的。
解決辦法,就是不要在.xml佈局檔案裡新增事件了,而是在自己的程式碼裡,獲取到這個控制元件,然後setOnClickListener(this);最後自己實現OnClickListener裡的方法,實現點選。