如何在Activity中运行Fragment?

时间:2018-10-23 10:42:05

标签: java android

我想在我的AddReminder中运行GoToReminder。你能告诉我怎么做吗?我尝试使用它,但是不起作用。如果您有任何疑问,请随时提问:)

Intent intent = new Intent(view.getContext(), GoToReminder.class);
startActivity(intent);

public class AddReminder extends AppCompatActivity {

    private static final String TAG = "AddReminder";

    @Override
    protected void onCreate(Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);
        setContentView(R.layout.add_reminder2);

        //HOW CAN I RUN FRAGMENT THERE

    }

}

public class GoToReminder extends Fragment {

    @Override
    public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
    }

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {

        View v = inflater.inflate(R.layout.main_screen, container, false);
        return v;

    }
}

3 个答案:

答案 0 :(得分:1)

您必须使用FragmentManager

FragmentManager fm = getSupportFragmentManager();
fm.beginTransaction()
.add(R.id.container, GoToReminder.newInstance())
.commit()

R.id.container 必须在add_reminder2.xml中声明,例如:

 <FrameLayout
    android:id="@+id/container"
    android:layout_width="match_parent"
    android:layout_height="wrap_content" />

请阅读文档,以了解如何使用FragmentTransaction

此外,您可以阅读Google的guide

答案 1 :(得分:0)

您可以在要显示片段的活动中添加Frame Layout

在AddReminder.xml

<FrameLayout
    android:id="@+id/frame"
    android:layout_width="match_parent"
    android:layout_height="200dp"></FrameLayout>

然后在AddReminder.Java中

    FragmentTransaction fragmentTransaction = getSupportFragmentManager().beginTransaction();
    fragmentTransaction.replace(R.id.frame, new GoToReminder()).addToBackStack(null).commit();

答案 2 :(得分:0)

您可以按照Android开发者文档中的说明添加片段,即

ggplot(dta, aes(x, value)) + 
    geom_boxplot() + 
    stat_compare_means(method = "anova", label.y = 4.8, 
                       data = dta %>% filter(x != "gr4"))

fragment_container是要在其中添加片段的布局的ID。这可以是框架布局,也可以是您要添加片段的其他布局。

此处有更多详细信息:https://developer.android.com/training/basics/fragments/fragment-ui#AddAtRuntime