Android之使用Fragment,XML无法相应onClick事件

通常,我们给Activity布局文件的Button设置点击事件函数,可以这样做:

然后在Activity处理OnClick()函数:

但如果这个布局文件是由Fragment加载的,那么就会报错:
java.lang.IllegalStateException: Could not find method onLogout(View) in a parent or ancestor Context for android:onClick attribute defined on view class android.widget.TextView with id 'id_logout'


原因在于:
Fragment不是布局器,不具备渲染视图的能力,虽然可以管理布局器,但它管理的布局器最终要加载到一个ViewGroup对象内,由ViewGroup对象来渲染,而ViewGroup并不知道每一个子控件来源于哪里。

解决方法:在Fragment的onActivityCreated 方法中执行以下代码:

 

 
原文地址:https://www.cnblogs.com/javalinux/p/14578807.html