标签:inf name 事务 contain cli 简单 xmlns ide code
Fragment,在平板应用中较为参见,把视图分为两个甚至多个模块。
(1)left_fragment
(2)right_fragment
(1)leftFragment(加载xml文件)
public class LeftleftFragment extends Fragment { @Nullable @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View view = inflater.inflate(R.layout.left_fragment,container,false);//动态加载xml return view; } }
(2)rightFragment
我是代码(同上);
<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="match_parent"> <fragment android:id="@+id/left_fragment" android:name="com.cenzhongman.myapplication.fragment.LeftleftFragment" android:layout_width="wrap_content" android:layout_height="match_parent" android:layout_weight="1"/> <fragment android:id="@+id/right_fragment" android:name="com.cenzhongman.myapplication.fragment.RightFragment" android:layout_width="wrap_content" android:layout_height="match_parent" android:layout_weight="1"/> </LinearLayout>
我是代码(同上,较少重复加载)
用两FrameLayout(强制左上角对齐的布局),来存放fragment,动态更新时候将会更换FrameLayout中的内容,也就是旗下的FrameLayout
<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="match_parent"> <FrameLayout android:id="@+id/left_fragment" android:layout_width="match_parent" android:layout_height="match_parent" android:layout_weight="1"> <fragment android:name="com.cenzhongman.myapplication.fragment.LeftleftFragment" android:layout_width="match_parent" android:layout_height="match_parent" android:id="@+id/fragment" /> </FrameLayout> <FrameLayout android:id="@+id/right_fragment" android:layout_width="match_parent" android:layout_height="match_parent" android:layout_weight="1"> <fragment android:name="com.cenzhongman.myapplication.fragment.RightFragment" android:layout_width="match_parent" android:layout_height="match_parent" /> </FrameLayout> </LinearLayout>
public void onClick(View v) { AnotherRightFragment anotherRightFragment = new AnotherRightFragment(); FragmentManager fragmentManager = getFragmentManager(); FragmentTransaction transaction = fragmentManager.beginTransaction(); transaction.replace(R.id.right_fragment, anotherRightFragment); transaction.commit(); }
1. 创建待添加的碎片实例。
2. 获取到 FragmentManager,在活动中可以直接调用 getFragmentManager()方法得到。
3. 开启一个事务,通过调用 beginTransaction()方法开启。
4. 向容器内加入碎片,一般使用 replace()方法实现,需要传入容器的 id 和待添加的碎
片实例。
5. 提交事务,调用 commit()方法来完成。
transaction.addToBackStack(null);//接收一个名字用于描述返回栈的状态,一般传入null即可
标签:inf name 事务 contain cli 简单 xmlns ide code
原文地址:http://www.cnblogs.com/cenzhongman/p/6045343.html