简体   繁体   English

单击按钮时从“活动”移动到“片段”

[英]Move from Activity to Fragment when button clicked

I used this code to move from Activity to Fragment when button clicked but when I run this code I find Activity is still in background. 单击按钮时,我使用此代码将“活动”移到“片段”,但是运行此代码时,我发现“活动”仍在后台。

 TopicsFragment fragment = new TopicsFragment();
            android.support.v4.app.FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
            transaction.replace(R.id.welcome_id, fragment);
            transaction.commit();

First of all, you need to understand what Activity and Fragments are. 首先,您需要了解什么是活动和片段。 You cannot move from Activity to Fragment. 您不能从活动转到片段。

You can inflate a Fragment or Fragments into an Activity. 您可以将一个或多个片段充气到活动中。 Fragments cannot be independent from an activity. 片段不能独立于活动。

A fragment must always be hosted in an activity and the fragment's lifecycle is directly affected by the host activity's lifecycle. 片段必须始终托管在活动中,并且片段的生命周期直接受到宿主活动的生命周期的影响。 For example, when the activity is paused, so are all fragments in it, and when the activity is destroyed, so are all fragments. 例如,活动被暂停时,其中的所有片段也将暂停;活动被销毁时,所有片段也将被暂停。 However, while an activity is running (it is in the resumed lifecycle state), you can manipulate each fragment independently, such as add or remove them. 但是,当一个活动正在运行时(它处于恢复的生命周期状态),您可以独立地操纵每个片段,例如添加或删除它们。 When you perform such a fragment transaction, you can also add it to a back stack that's managed by the activity—each back stack entry in the activity is a record of the fragment transaction that occurred. 执行此类片段事务时,还可以将其添加到由活动管理的后台堆栈中-活动中的每个后台堆栈条目都是发生的片段事务的记录。 The back stack allows the user to reverse a fragment transaction (navigate backwards), by pressing the Back button. 后退堆栈允许用户通过按“后退”按钮来反转片段事务(向后导航)。

Source: https://developer.android.com/guide/components/fragments 资料来源: https : //developer.android.com/guide/components/fragments

If you don't want to see the activity after entering into fragment, you could extend from DialogFragment and make it fullscreen, there are many examples, google it using "android fullscreen dialogfragment". 如果您不想在进入片段后看到活动,则可以从DialogFragment扩展并使其全屏显示,有很多示例,可以使用“ android fullscreen dialogfragment”在Google上进行搜索。

and here is DialogFragment doc . 这是DialogFragment doc

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM