完整项目代码
https://github.com/Phil-tom/Android-The-First-Line-of-Code/tree/main/Chapter4/FragmentTest
上篇文章讲了在布局中添加碎片的方法,不过碎片的强大之处在于,它可以在程序运行时动态地添加到活动中。
新建another_right_fragment.xml
<?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"
android:background="#ffff99"
android:orientation="vertical">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center_horizontal"
android:text="This is another right fragment"
android:textSize="20sp" />
</LinearLayout>
新建AnotherRightFragment类
import androidx.fragment.app.Fragment;
public class AnotherRightFragment extends Fragment {
@Override
public View onCreateView(LayoutInflater inflater,ViewGroup container,Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.another_right_fragment, container, false);
return view;
}
}
修改activity_main.xml,将右侧碎片替换成FrameLayout中。
FrameLayout,这是Android中最简单的一种布局,所有控件都会默认摆放在控件的左上角。
<?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"
android:orientation="horizontal">
<fragment
android:id="@+id/left_fragment"
android:name="com.zzz.fragmenttest.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" />
</LinearLayout>
MainActivity
在代码中向FrameLayou里添加内容,从而实现动态添加碎片的功能。
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button button = (Button) findViewById(R.id.button);
button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.button:
replaceFragment(new AnotherRightFragment());
break;
default:
break;
}
}
});
replaceFragment(new RightFragment());
}
private void replaceFragment(Fragment fragment) {
FragmentManager fragmentManager = getSupportFragmentManager();
FragmentTransaction transaction = fragmentManager.beginTransaction();
transaction.replace(R.id.right_layout, fragment);
transaction.commit();
}
}
动态添加碎片主要分五步:
(1)创建待添加的碎片实例
(2)获取FragmentManager,在活动中可以直接调用getSupportFragmentManager()
(3)开启一个事务,通过fragmentManager.beginTransaction()
(4)向容器内添加或替换碎片,transaction.replace
(5)提交事务,commit
点击按钮前:
点击按钮后