解决方法示例:
import androidx.fragment.app.FragmentManager;
import androidx.fragment.app.FragmentTransaction;
FragmentManager fragmentManager = getSupportFragmentManager();
FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
YourFragment fragment = new YourFragment();
fragmentTransaction.add(R.id.container, fragment); // 添加Fragment到容器中
// 或者
fragmentTransaction.replace(R.id.container, fragment); // 替换容器中的Fragment
fragmentTransaction.commit();
完整的示例代码如下:
import androidx.appcompat.app.AppCompatActivity;
import androidx.fragment.app.FragmentManager;
import androidx.fragment.app.FragmentTransaction;
import android.os.Bundle;
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// 获取FragmentManager
FragmentManager fragmentManager = getSupportFragmentManager();
// 开始一个新的Fragment事务
FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
// 添加或替换Fragment
YourFragment fragment = new YourFragment();
fragmentTransaction.add(R.id.container, fragment); // 添加Fragment到容器中
// 或者
fragmentTransaction.replace(R.id.container, fragment); // 替换容器中的Fragment
// 提交事务
fragmentTransaction.commit();
}
}
请注意,上述示例假设您的布局文件中有一个id为"container"的容器,用于容纳Fragment。您需要根据自己的布局和需求进行相应的更改和调整。