Android之使用Fragment无法相应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 方法中执行代码

--------------------- 
作者:lvxiangan 
来源:CSDN 
原文:https://blog.csdn.net/LVXIANGAN/article/details/78811051 
版权声明:本文为博主原创文章,转载请附上博文链接!

猜你喜欢

转载自blog.csdn.net/TYtrack/article/details/88881921