Android中如何为Fragment中的按钮添加监听事件

来源:互联网 发布:淘宝客服绩效是什么 编辑:程序博客网 时间:2024/05/22 14:21

最近在写一个类似于微信选项卡切换的Demo,每一个切换的页面是用Fragment来实现的。写好了切换效果,但是又遇到了一个问题,如何为每个Fragment中的按钮等元素添加监听事件呢?看了郭大神的博客,恍然大悟。
先放上我的代码:
Fragment的xml文件代码:

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"      android:layout_width="match_parent"      android:layout_height="match_parent"      android:background="#00ff00" >      <Button        android:id="@+id/button"        android:layout_width="wrap_content"          android:layout_height="wrap_content"          android:text="This is fragment"  />  </LinearLayout>  

Fragment中的代码:

public class Fragment extends Fragment {    @Override      public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {        return inflater.inflate(R.layout.fragment, container, false);      }    @Override      public void onActivityCreated(Bundle savedInstanceState) {          super.onActivityCreated(savedInstanceState);          Button button = (Button) getActivity().findViewById(R.id.button);          button.setOnClickListener(new OnClickListener() {      @Override      public void onClick(View v) {                  Toast.makeText(getActivity(), "Clicked", Toast.LENGTH_LONG).show();              }          });      }  }

代码中最关键的要注意:
在onCreateView中返回Fragment的布局文件
在onActivityCreated中通过getActivity()获取到Fragment关联的Activity,在onActivityCreated中为按钮添加监听事件。
关于Fragment的生命周期参考郭大神这篇博客Fragment详解

1 0
原创粉丝点击