Fragment基础控件的使用

本文介绍了Android开发中Fragment的基础使用,包括如何进行fragment切换、如何通过FragmentManager管理回退栈,以及如何在Activity与Fragment间传递数据。通过实例展示了动态替换Fragment以及接收传入参数的方法。

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

Fragment作为Android最基本,最重要的基础概念之一,在开发中经常会和他打交道。使用FragmentManager实现fragment切换已经无法满足市场的需求,当存在多个同种业务的fragment的时,需要使用fragment嵌套,一个activity对应多个fragment,在其中一个fragment中加载同种业务的fragment。

退回栈

ContentFragment fragment = new ContentFragment(); FragmentTransaction ft = getSupportFragmentManager().beginTransaction(); ft.replace(R.id.fl_content,fragment); ft.addToBackStack(“name”); ft.commit();

清空退回栈

FragmentManager fm= getFragmentManager(); int count = fm.getBackStackEntryCount(); for (int i = 0; i < count; ++i) {     fm.popBackStack(); }

如下实例进行activity通过setArguments发送数据

public void click(View view) {         //取到输入的值         String string = editText.getText().toString();         //创建fragment对象         ShowContextFragment showContextFragment = new ShowContextFragment();         //创建bundle         Bundle bundle = new Bundle();         bundle.putString("key",string);         //给fragment对象赋值         showContextFragment.setArguments(bundle);         //动态修改fragment         fragmentManager = getSupportFragmentManager();         fragmentTransaction = fragmentManager.beginTransaction();         fragmentTransaction.replace(R.id.linear_layout_id,showContextFragment);         fragmentTransaction.commit();     }

fragment通过getArguments获得数据

public class ShowContextFragment extends Fragment {     private TextView textView;     public ShowContextFragment() {     }     //现在text里面的值是"hello_blank_fragment",思路就是拿到控件,重新赋值即可.     @Override     public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {         View inflate = inflater.inflate(R.layout.fragment_show_context, container, false);         //1 拿控件         textView = inflate.findViewById(R.id.context_tv_id);         //2 给控件赋值         Bundle arguments = getArguments();         if(arguments != null){ //第一次启动一定为null,所以要判断一下             String key = arguments.getString("key");             textView.setText(key);         }         return inflate;     } }

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值