(2)静态的使用Fragment

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;
    }

}

  • 2
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值