简体   繁体   English

如何从另一个片段调用活动。?

[英]How to call activity from another fragment.?

I already know how to make a fragment in Android.我已经知道如何在 Android 中制作片段。 I want to open another activity in the same fragment on a button click event.我想在按钮单击事件的同一片段中打开另一个活动。 The button is inside a fragment class.该按钮位于片段 class 内。

How do I do that?我怎么做?

There are two possibilities depending on what you need:根据您的需要,有两种可能性:

  • Fragment Receive Result that demonstrates starting a new Activity from a Fragment, and receiving a result back from it. Fragment Receive Result演示从 Fragment 开始一个新的 Activity,并从它接收返回的结果。
  • setTargetFragment may be used, for example, if this fragment is being started by another, and when done wants to give a result back to the first.可以使用setTargetFragment ,例如,如果此片段正在由另一个片段启动,并且完成后希望将结果返回给第一个片段。 An example is available here 这里有一个例子

All Fragment-to-Fragment communication is done through the associated Activity.所有 Fragment 到 Fragment 的通信都是通过关联的 Activity 完成的。 Two Fragments should never communicate directly.两个 Fragment 永远不应该直接通信。

Here are some tutorials with example这是一些带有示例的教程

EDIT: April 2013编辑:2013 年 4 月

I like @AlexLockwood's comment.我喜欢@AlexLockwood 的评论。

In the case that one fragment starts another fragment, it's fine to just use setTargetFragment(Fragment, int) and communicate with it directly by calling getTargetFragment() .在一个片段开始另一个片段的情况下,只需使用setTargetFragment(Fragment, int)并通过调用getTargetFragment()直接与其通信就可以了。 Communicating with Fragments through the activity is usually a good idea because it keeps your fragments loosely coupled from one another.通过 Activity 与 Fragments 通信通常是一个好主意,因为它使您的 Fragment 彼此之间保持松散耦合。

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

相关问题 如何打开另一个片段的活动? - How to open activity from another fragment.? 将数据从一个片段发送到另一片段时出错。 (两个片段都由一个活动托管) - Error sending data from one fragment to another fragment. ( Both fragments are hosted by one activity) 从片段创建新的listadapter。 知道如何通过活动而不是片段来做到这一点 - Create new listadapter from a fragment. Know how to do it from an activity but not from a fragment 将数据从片段传递到另一个片段。 片段未附加到上下文 - Passing data from fragment to another fragment. Fragment not attached to a context 我在片段中有一个线性布局。 如何从活动中动态添加视图? - I've a linear layout in a fragment. How to dynamically add a view to it from the activity? 从另一个片段/活动调用片段中的方法 - Call method in fragment from another fragment/activity Android:通过片段预览相机。 活动还可以 - Android: camera preview through a fragment. Ok from activity 无法将数据从“活动”传递到片段。 得到NULL - Unable to pass data from Activity to fragment. getting NULL 试图通过按下按钮来打开活动片段。 什么都没发生 - Trying to open activity from button press in fragment. Nothing happens 如何从不是父项的另一个活动中调用片段? - How to call a fragment from another activity which is not parent?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM