(2)静态的使用Fragment

来源:互联网 发布:在线js格式化工具 编辑:程序博客网 时间:2024/05/21 17:52

1.思路

这是使用Fragment最简单的一种方式,把Fragment当成普通的控件,直接写在Activity的布局文件中。步骤:

1、继承Fragment,重写onCreateView决定Fragemnt的布局

2、在Activity中声明此Fragment,就当和普通的View一样

2.例子


在Activity中使用标题布局和内容布局,我们可以引入两个fragment,分别对应标题和内容。此时我们定义的fragment和普通的View用法一样。此时activity_main.xml布局如下:

<?xml version="1.0" encoding="utf-8"?><LinearLayout    xmlns:android="http://schemas.android.com/apk/res/android"    xmlns:app="http://schemas.android.com/apk/res-auto"    xmlns:tools="http://schemas.android.com/tools"    android:layout_width="match_parent"    android:layout_height="match_parent"    android:orientation="vertical"    android:background="#f5f4f9"    tools:context="xzy.com.myfragmentdemo.TestStaticFragmentActivity">    <fragment        android:id="@+id/id_fragment_title"        android:name="xzy.com.myfragmentdemo.titleFragment"        android:layout_width="match_parent"        android:layout_height="45dp"        />    <fragment        android:id="@+id/id_fragment_content"        android:name="xzy.com.myfragmentdemo.ContentFragment"        android:layout_width="match_parent"        android:layout_height="match_parent"        /></LinearLayout>
titleFragment和ContentFragment是我们自定义的fragment,它们均继承自Fragment.

我们发现把Fragment当成普通的View一样声明在Activity的布局文件中,然后所有控件的事件处理等代码都由各自的Fragment去处理,瞬间觉得Activity好干净有木有~~代码的可读性、复用性以及可维护性瞬间提升。

下面是在titleFragment中处理点击事件

package xzy.com.myfragmentdemo;import android.app.Fragment;import android.os.Bundle;import android.view.LayoutInflater;import android.view.View;import android.view.ViewGroup;import android.widget.ImageView;/** * A simple {@link Fragment} subclass. */public class titleFragment extends Fragment {    private ImageView mLeftBtn;    public titleFragment() {        // Required empty public constructor    }    @Override    public View onCreateView(LayoutInflater inflater, ViewGroup container,                             Bundle savedInstanceState) {        // Inflate the layout for this fragment        View view = inflater.inflate(R.layout.fragment_title, container, false);        mLeftBtn = (ImageView)view.findViewById(R.id.iv_left_icon);        mLeftBtn.setOnClickListener(new View.OnClickListener() {            @Override            public void onClick(View v) {                //todo            }        });        return view;    }}