Fragment基础使用

本文介绍了Android中Fragment的基础使用,包括XML定义和动态添加Fragment,替换Fragment的操作,以及Fragment与Activity之间的通信。强调了Fragment不应直接通信,而应通过Activity传递消息。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

1、添加Fragment的方式有两种,一种是定义在XML文件中,一种是动态添加(需要xml中定义一个空的FrameLayout来作为容器)

动态添加
创建想要添加的Fragment

HeadlinesFragment firstFragment = new HeadlinesFragment();

如果希望传递参数可以这样设置

firstFragment.setArguments(getIntent().getExtras());

获取SupportFragmentManager、开始事务beginTransaction、进行的是添加操作add、提交commit

getSupportFragmentManager().beginTransaction().add(R.id.fragment_container,firstFragment).commit();

这里需要注意一点就是当前Activity需要继承FragmentActivity或者ActionBarActivity等支持Fragment。

获取定义在Xml中的Fragment

ArticleFragment articleFrag = (ArticleFragment)
getSupportFragmentManager().findFragmentById(R.id.article_fragment);

定义在xml文件中的Fragment不可动态移除掉

2、进行替换Fragment操作

 FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
 transaction.replace(R.id.fragment_container, newFragment);  

如果想回到替换前的Fragment,添加返回导航

 transaction.addToBackStack(null);
 transaction.commit();

3、Fragment to Activity communication

在Fragment中定义一个接口,需要在Activity中实现该接口,在onAttach(Activity activity)方法中判断Activity是否已实现了接口。
Define an Interface

// Container Activity must implement this interface
    public interface OnHeadlineSelectedListener {
        public void onArticleSelected(int position);
    }

 @Override
    public void onAttach(Activity activity) {
        super.onAttach(activity);

        // This makes sure that the container activity has implemented
        // the callback interface. If not, it throws an exception
        try {
            mCallback = (OnHeadlineSelectedListener) activity;
        } catch (ClassCastException e) {
            throw new ClassCastException(activity.toString()
                    + " must implement OnHeadlineSelectedListener");
        }
    }

通过在Fragment中调用接口中的方法,即可与Activity communication。

4、All Fragment-to-Fragment communication is done through the associated Activity. Two Fragments should never communicate directly.

5、Deliver a Message to a Fragment

在Activity中获取Fragment的实例,判断是否非空,调用Fragment中的公共函数,通过参数传递Message。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值