问题:

下面是一个在fragment的布局中定义的一个点击事件

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类中的一个内部类

acd5caca0ad9?utm_campaign=maleskine&utm_content=note&utm_medium=seo_notes&utm_source=recommendation

image.png

看一下属性就明白这个类似干什么的了(膜拜)

mHostView:定义了onClick属性的view

mMethodName:方法名称

mResolvedContext:反射对象

mResolvedMethod:反射方法

所以view是通过反射的方式来调用方法的(大家应该不看源码都知道的),这里的mResolvedContext 是通过View.getContext获取的

acd5caca0ad9?utm_campaign=maleskine&utm_content=note&utm_medium=seo_notes&utm_source=recommendation

image.png

那么,view的context中为什么找不到方法呀,我都定义了不是吗。但是,注意一下,我们定义的方法是在Fragment中,fragment,fragment是context吗?当然不是,看看fragment class的定义

acd5caca0ad9?utm_campaign=maleskine&utm_content=note&utm_medium=seo_notes&utm_source=recommendation

image.png

fragment有生命周期,是视图的管理者,并不是context,所以你把方法定义在fragment中系统当然找不到。

那么view的context是谁呢?fragment的使用范围里,除了activity是Context外还有谁呢(滑稽)。

Logo

Agent 垂直技术社区,欢迎活跃、内容共建。

更多推荐