This question already has answers here:
How to open a Fragment on button click from a fragment in Android

(3 个回答)


4年前关闭。




我尝试了以下代码:
Intent in= new Intent(Activity1.this,Fragment.class);
startactivity(in);

最佳答案

这不是 how fragments work , fragment 必须附加到 Activity 。要获得所需的效果,您必须启动一个包含您希望显示的 fragment 的新 Activity ,或者在当前 Activity 中显示新 fragment 。

为了决定采用哪种方法,我会考虑您希望 Fragment 如何影响您的界面导航。如果您希望用户能够使用 Back 按钮返回上一个 View ,您应该启动一个新的 Activity 。否则,您应该用新的 Activity 替换当前 Fragment 中的 View 。

虽然可以将 Fragment 添加到后台堆栈中,但只有当您对用户界面的结构有信心时,我才会尝试这样做。

要在当前 Activity 中显示新 fragment ,您可以使用 FragmentTransaction :

Fragment fragment = CustomFragment.newInstance();

FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();

transaction.replace(R.id.container_layout, fragment).commit();

10-07 19:27
查看更多