Fragment的概念和使用

一:Fragment的概念

1:Fragment本身的中文意思是“碎片”,可以将Activity拆分成几个完全独立封装的可重用的组件,每个组件有    自己的生命周期和ui布局。


二:Fragment的静态加载

布局文件

<?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"
tools:context="com.example.myapplication.MainActivity">

<fragment
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_weight="1"
android:name="com.example.myapplication.HelloFragment"
android:id="@+id/hello_fragment"/>
<fragment
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_weight="1"
android:id="@+id/list_fragment"
android:name="com.example.myapplication.ListFragment"/>

</LinearLayout>

结果


三:Fragment的动态加载

不需要在主布局文件中去声明fragment的,而是直接在java代码中去添加

FragmentTransaction方法:

Fragment事物对象,对Fragment进行添加(add)、移除(remove)、替换(replace)、提交(commit)等操作的对象。


viewpager页码的滑动

主要代码:

<android.support.v4.view.ViewPager
android:id="@+id/vp"
android:layout_width="match_parent"
android:layout_height="match_parent">
</android.support.v4.view.ViewPager>
ViewPager+Fragment实现页卡滑动

主要步骤:

在建完需要的Fragment之后,新建一个适配器Adapter,继承FragmentPagerAdapter,主要代码如下:

List<Fragment> fragmentList;
    public ViewpagerAdapter(FragmentManager fm,List<Fragment> fragmentList) {
        super(fm);
        this.fragmentList=fragmentList;
    }

    @Override
    public Fragment getItem(int position) {
        return fragmentList.get(position);
    }

    @Override
    public int getCount() {
        return fragmentList.size();
    }

Activity类:

        friend = findViewById(R.id.friend);
        my = findViewById(R.id.my);
        //绑定id到点击事件
        cont.setOnClickListener(this);
        friend.setOnClickListener(this);
        my.setOnClickListener(this);

        vp = findViewById(R.id.vp);

        cont_view = findViewById(R.id.cont_view);
        friend_view = findViewById(R.id.friend_view);
        my_view = findViewById(R.id.my_view);

        contFragment = new ContFragment();
        friendFragment = new FriendFragment();
        myFragment = new MyFragment();

        fragmentList.add(contFragment);
        fragmentList.add(friendFragment);
        fragmentList.add(myFragment);

        ViewpagerAdapter adapter = new ViewpagerAdapter(getSupportFragmentManager(), fragmentList);
        vp.setAdapter(adapter);
        vp.setOnPageChangeListener(new ViewPager.OnPageChangeListener() {
            @Override
            public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

            }

            @Override
            public void onPageSelected(int position) {
                cont_view.setBackgroundColor(Color.GRAY);
                friend_view.setBackgroundColor(Color.GRAY);
                my_view.setBackgroundColor(Color.GRAY);
                switch (position) {
                    case 0:
                        cont_view.setBackgroundColor(Color.BLUE);
                        break;
                    case 1:
                        friend_view.setBackgroundColor(Color.BLUE);
                        break;
                    case 2:
                        my_view.setBackgroundColor(Color.BLUE);
                        break;
                    default:
                        break;
                }

            }

            @Override
            public void onPageScrollStateChanged(int state) {

            }
        });
    }

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.cont:
                //点中哪个页卡就到哪个页面
                vp.setCurrentItem(0);
                break;
            case R.id.friend:
                vp.setCurrentItem(1);
                break;
            case R.id.my:
                vp.setCurrentItem(2);
                break;
            default:
                break;
        }
    }
}

这样就实现了页卡的滑动和点击。


Fragment的生命周期

Fragment必须是依存于Activity而存在的。

因此,Activity的生命周期会直接影响到Fragment的生命周期。

 

onAttach()

onCreate()

onCreateView()

onActivityCreated()

onStart()

onResume()

onPause()

onStop()

onDestroyView()

onDestroy()

onDetach()

代码演示:

public class FriendFragment extends Fragment {

    private String TAG="FriendFragment";

    public FriendFragment() {
        // Required empty public constructor
    }


    @Override
    public void onAttach(Context context) {
        super.onAttach(context);
        Log.d(TAG, "onAttach:********* ");
    }

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        Log.d(TAG, "onCreate: *********");
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        Log.d(TAG, "onCreateView: *********");
        return inflater.inflate(R.layout.fragment_friend, container, false);
    }
    @Override
    public void onStart() {
        super.onStart();
        Log.d(TAG, "onStart: *********");
    }

    @Override
    public void onResume() {
        super.onResume();
        Log.d(TAG, "onResume: *********");
    }

    @Override
    public void onPause() {
        super.onPause();
        Log.d(TAG, "onPause: *********");
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        Log.d(TAG, "onDestroyView: *********");
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        Log.d(TAG, "onDestroy:*********");
    }

    @Override
    public void onDetach() {
        super.onDetach();
        Log.d(TAG, "onDetach: *********");
    }

}


Fragment与Activity的通信

可以在Fragment上控制Activity

假如在Fragment的button可以在Activity的Textview上出现标题

主要代码

Activity的XML:

<TextView
        android:id="@+id/title_tv"
        android:layout_width="match_parent"
        android:layout_height="50dp" />

Activity代码:

将想要的内容(title)传至Fragment

public void modifyTitie(String title){
        title1.setText(title);

Fragment的XML:

<Button
        android:id="@+id/one_bt"
        android:layout_width="100dp"
        android:layout_height="50dp"
        android:text="我是张国庆" />

Fragment代码:

View view=inflater.inflate(R.layout.fragment_one,container,false);
        button=view.findViewById(R.id.one_bt);
        button.setOnClickListener(this);

        return view;

    }

    @Override
    public void onClick(View v) {
        Main5Activity main5Activity= (Main5Activity) getActivity();
        main5Activity.modifyTitie("我是张国庆");
    }

实现Activity传值Fragment

类似Activity之间的通信intent,这里用Bundle

Activity代码:

Bundle bundle=new Bundle();
        bundle.putString("name","我是满少爷");
        oneFragment.setArguments(bundle);

Fragment代码:

 Bundle bundle = getArguments();
        String name = bundle.getString("name");
        button.setText(name);










  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
Fragment 是 Android 中的一种组件,用于构建灵活且可重用的用户界面模块。它可以嵌入到 Activity 中,允许在一个 Activity 中同时展示多个界面。以下是使用 Fragment 的一般步骤: 1. 创建一个继承自 Fragment 的子类,或者使用现有的 Fragment 子类。 ```java public class YourFragment extends Fragment { // 在这里定义 Fragment 的逻辑和界面组件 } ``` 2. 在 Fragment 中实现 `onCreateView()` 方法,用于创建和返回该 Fragment 的布局。 ```java @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { // 使用布局填充器(inflater)将布局文件转换为 View 对象 View view = inflater.inflate(R.layout.your_fragment_layout, container, false); // 在这里可以对 View 对象进行初始化和设置事件监听器等操作 return view; } ``` 3. 在需要使用 Fragment 的 Activity 中,通过 FragmentManager 开始一个事务,并添加、替换或移除 Fragment。 ```java FragmentTransaction transaction = getSupportFragmentManager().beginTransaction(); // 添加 Fragment transaction.add(R.id.fragment_container, new YourFragment()); // 替换 Fragment transaction.replace(R.id.fragment_container, new YourFragment()); // 移除 Fragment transaction.remove(existingFragment); // 提交事务 transaction.commit(); ``` 4. 在 Activity 的布局文件中添加一个容器,用于承载 Fragment。 ```xml <FrameLayout android:id="@+id/fragment_container" android:layout_width="match_parent" android:layout_height="match_parent" /> ``` 这样,你就可以在 Activity 中使用 Fragment 了。通过添加、替换或移除 Fragment,你可以动态地切换不同的界面模块,从而实现更灵活和可重用的用户界面。 希望以上解释对你有所帮助!如有任何疑问,请随时提问。

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值