如何在Android中有意和无意地从活动中单击按钮上打开片段? [英] How to open fragment on a button click from an activity either with intent and without intent in android?

查看:60
本文介绍了如何在Android中有意和无意地从活动中单击按钮上打开片段?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我尝试了以下代码:

Intent in= new Intent(Activity1.this,Fragment.class);
startactivity(in);

推荐答案

这不是如何片段工作,片段必须附加到 Activity .为了获得理想的效果,您必须启动一个新的包含您要显示的片段的 Activity ,或在当前的 Activity 中显示该新片段.

This is not how fragments work, fragments must be attached to an Activity. To get your desired effect you must either start a new Activity that contains the fragment you wish to show, or display the new fragment in the current Activity.

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

In order to decide between which approach to take, I would consider how you want the Fragment to affect the navigation of your interface. If you want the user to be able to get back to the previous view by using the Back button, you should start a new Activity. Otherwise you should replace a view in your current Activity with the new Fragment.

尽管,有可能在后堆栈中添加 Fragment ,但只有在您对用户界面的结构充满信心的情况下,我才会尝试这样做.

Though, it is possible to add a Fragment to the back stack, I would only attempt to do so if you are confident with the structure of your user interface.

要在当前的 Activity 中显示新的片段,可以使用 FragmentTransaction :

To show a new fragment in the current Activity you can use a FragmentTransaction:

Fragment fragment = CustomFragment.newInstance();

FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();

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

这篇关于如何在Android中有意和无意地从活动中单击按钮上打开片段?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆