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 方法中执行以下代码:

  • 7
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Fragment中添加逻辑可以分为以下几个步骤: 1. 在布局文件中添加相应的控件。 2. 在Fragment中获取控件,并设置相应的监听器。 3. 在监听器中实现相应的逻辑操作。 示例代码如下: 布局文件: ``` <LinearLayout android:layout_width="match_parent" android:layout_height="match_parent" android:gravity="center" android:orientation="vertical"> <TextView android:id="@+id/text_view" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="这是一个Fragment"/> <Button android:id="@+id/button" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="点击"/> </LinearLayout> ``` Fragment中添加逻辑: ``` public class MyFragment extends Fragment { private TextView textView; private Button button; @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View view = inflater.inflate(R.layout.fragment_layout, container, false); textView = view.findViewById(R.id.text_view); button = view.findViewById(R.id.button); button.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { // 在这里实现按钮点击的逻辑操作 textView.setText("按钮被点击了!"); } }); return view; } } ``` 以上代码中,我们在Fragment的onCreateView()方法中获取了布局文件中的TextView和Button控件,并设置了Button的点击监听器。在监听器中,我们实现了点击按钮后TextView的文本内容改变的逻辑操作。 当然,具体的逻辑操作根据需求而定,可以根据需要添加相应的逻辑代码。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值