@Override public void onClick(View v) { switch (v.getId()){ case R.id.btn1: replaceFragment(new AnotherRightFragment(),"anotherRightFragment"); // //在activity中获得fragment实例 // AnotherRightFragment ar = (AnotherRightFragment)getFragmentManager().findFragmentByTag("anotherRightFragment"); // Log.d(TAG, "onClick: "+ar); // ar.setText("文字哈"); break; case R.id.btn2: AnotherRightFragment ar = (AnotherRightFragment)getFragmentManager().findFragmentByTag("anotherRightFragment"); Log.d(TAG, "onClick: "+ar); ar.setText("文字哈"); break; default: break; } } /** *动态添加fragment */ private void addFragment(Fragment fragment){ FragmentManager fm = getFragmentManager(); fm.beginTransaction().add(R.id.right_layout,fragment).commit(); // transaction.addToBackStack(null); } /** *动态添加fragment */ private void replaceFragment(Fragment fragment,String tag){ FragmentManager fm = getFragmentManager(); fm.beginTransaction().replace(R.id.right_layout,fragment,tag).commit(); }
在替换之后马上
AnotherRightFragment ar = (AnotherRightFragment)getFragmentManager().findFragmentByTag("anotherRightFragment");会获取不到这个fragment。findFragmentById是获取 xml布局文件显示<fragment android:name="[email protected]/fid"/> 声明的。findFragmentByTag能动态获取查了下fragment的生命周期, 添加一个碎片->onAttach()->onCreate()->onCreateView()
/** *动态添加fragment */private void replaceFragment(Fragment fragment,String tag){ FragmentManager fm = getFragmentManager(); FragmentTransaction tc = fm.beginTransaction(); tc.replace(R.id.right_layout,fragment,tag); tc.addToBackStack(null); tc.commit(); //立即执行 fm.executePendingTransactions();}add或者replace只是添加到任务,如果立即执行得加上executePendingTransactions。这样才能紧跟着通过fragmentmanager获取fragment
manager.findFragmentById(); //根据ID来找到对应的Fragment实例,主要用在静态添加fragment的布局中,因为静态添加的fragment才会有ID
manager.findFragmentByTag();//根据TAG找到对应的Fragment实例,主要用于在动态添加的fragment中,根据TAG来找到fragment实例
manager.getFragments();//获取所有被ADD进Activity中的Fragment
http://blog.csdn.net/harvic880925/article/details/44927375
时间: 2024-10-21 13:07:42