动态更好fragment:
1. MainActivity
package com.example.fragmenttest;
import androidx.appcompat.app.AppCompatActivity;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentManager;
import androidx.fragment.app.FragmentTransaction;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
public class MainActivity extends AppCompatActivity implements View.OnClickListener{
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button button = (Button) findViewById(R.id.button);//button必须先具现出来,否则会返回null
button.setOnClickListener(this);
replaceFragment(new FragmentRight());
}
@Override
public void onClick(View view) {
switch (view.getId()){
case R.id.button:
replaceFragment(new AnotherFragment());
break;
default:
break;
}
}
//更换fragment
private void replaceFragment(Fragment fragment){
//获取所在fragment 的父容器的管理器
FragmentManager fragmentManager = getSupportFragmentManager();
//获取操作事务的对象,所谓的事务,就是可以一次性添加多个操作。比如Fragment使用方法中的add,replace,remove,remove,add可以组成是一个事务。
FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
fragmentTransaction.replace(R.id.fragment_layout, fragment);
fragmentTransaction.addToBackStack(null); //按返回键后,不会退出屏幕且显示之前的fragment
fragmentTransaction.commit();
}
}
2. Activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
<fragment
android:id="@+id/fragment_left"
<--com.example.fragmenttest.FragmentLeft 必须包含这个类的完整路径-->
android:name="com.example.fragmenttest.FragmentLeft"
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_weight="1" />
<FrameLayout
android:id="@+id/fragment_layout"
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_weight="1">
</FrameLayout>
</LinearLayout>
3. FragmentLeft.class
package com.example.fragmenttest;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import androidx.fragment.app.Fragment;
public class FragmentLeft extends Fragment {
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState){
View view = inflater.inflate(R.layout.fragment_left, container, false);
return view;
}
}
4. fragement_left.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">
<Button
android:id="@+id/button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center_horizontal"
android:text="button"/>
</LinearLayout>