1. 创建要添加的fragment
fragment_right.xml
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="@color/colorPrimaryDark">
<TextView
android:id="@+id/text"
android:layout_width="wrap_content"
android:layout_height="wrap_content"/>
</LinearLayout>
fragment_another_right.xml
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#ffff00">
<TextView
android:id="@+id/another_textView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="新的右边"/>
</LinearLayout>
2. activity_main.xml中添加fragment
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="horizontal">
<fragment
android:id="@+id/left_fragment"
android:name="com.example.a123.fragmenttext.LeftFragment"
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_weight="1"/>
<FrameLayout
android:id="@+id/right_layout"
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_weight="1">
</FrameLayout>
</LinearLayout>
3. 通过beginTransaction开启事务
repalce 替换fragment
commit 提交事务
public class MainActivity extends AppCompatActivity implements View.OnClickListener
{
@Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button button = findViewById(R.id.button);
button.setOnClickListener(this);
replaceFragment(new RightFragment());
}
@Override
public void onClick(View v)
{
switch (v.getId()) {
case R.id.button:
replaceFragment(new AnOtherFragment());
break;
default:
break;
}
}
private void replaceFragment(Fragment fragment)
{
FragmentManager fragmentManager = getSupportFragmentManager();
// 开启事务
FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
fragmentTransaction.replace(R.id.right_layout, fragment);
// back键返回上一个fragment
fragmentTransaction.addToBackStack(null);
// 提交事务
fragmentTransaction.commit();
}
}
4. fragment 与 activity 间通信
在fragment 中 获取activity实例
MainActivity mainActivity = (MainActivity) getActivity();
在activity中获取fragment的实例
LeftFragment fragment = getFragmentManager().findFragmentById(R.id.left_fragment);
5. fragment的生命周期
运行状态:碎片可见
暂停状态:活动暂停
停止状态:活动停止
销毁状态:活动销毁
6.回调方法
onAttach():碎片与活动建立关联时
onCreateView():为碎片创建视图时
onActivityCreated();与碎片关联的活动创建完成时
onDestoryView();与碎片关联的视图移除时
onDetach();当碎片与活动解除关联时调用