Android Fragment的佈局中使用android:onClick 屬性時需要注意的問題
問題:
下面是一個在fragment的佈局中定義的一個點選事件
<ImageView android:layout_width="wrap_content" android:layout_height="wrap_content" android:contentDescription="@null" android:onClick="onMessageViewClick" android:clickable="true" android:focusable="true" />
按照常規操作,我們需要在宿主中定義一個名為 onMessageViewClick 的public 方法
public void onMessageViewClick(View v) { dosomething... }
這樣看起來沒什麼問題,但是跑起來直接報錯:
java.lang.IllegalStateException: Could not find method xxx in a parent or ancestor Context for android:onClick attribute defined on view class
解決方法:
在持有fragment的activity中定義改方法即可
原因分析:
1.報錯資訊:無法在對應的context中找到名為 onMessageViewClick 的方法(其實這裡已經說的很明白了,找不到方法,在view的context中)
那看一下當我們點選view的時候系統是怎麼尋找對應的方法的:
直接上截圖,下面是view類中的一個內部類

image.png
看一下屬性就明白這個類似幹什麼的了(膜拜)
mHostView:定義了onClick屬性的view
mMethodName:方法名稱
mResolvedContext:反射物件
mResolvedMethod:反射方法
所以view是通過反射的方式來呼叫方法的(大家應該不看原始碼都知道的),這裡的mResolvedContext 是通過View.getContext獲取的

image.png
那麼,view的context中為什麼找不到方法呀,我都定義了不是嗎。但是,注意一下,我們定義的方法是在Fragment中,fragment,fragment是context嗎?當然不是,看看fragment class的定義

image.png
fragment有生命週期,是檢視的管理者,並不是context,所以你把方法定義在fragment中系統當然找不到。
那麼view的context是誰呢?fragment的使用範圍裡,除了activity是Context外還有誰呢(滑稽)。