如何将变量从Activity传递给Fragment,并将其传回去?

126 android android-fragments android-activity

我目前正在制作一个Android应用程序,我想在活动和片段之间传递一个日期.我的活动有一个按钮,用于打开片段:DatePickerFragment.

在我的活动中,我显示了一个日期,我想用片段修改它.所以我想将日期传递给datepicker,然后将其发送回活动.

我尝试了很多解决方案,但都没有.简单的方法会传递一个参数,但这不能用碎片来完成.

jpa*_*ogo 204

要将信息传递给片段,请在创建时调整setArguments,然后可以在片段的onCreate或onCreateView方法上检索此参数.

在片段的newInstance函数中,添加要发送给它的参数:

/**
 * Create a new instance of DetailsFragment, initialized to
 * show the text at 'index'.
 */
public static DetailsFragment newInstance(int index) {
    DetailsFragment f = new DetailsFragment();
    // Supply index input as an argument.
    Bundle args = new Bundle();
    args.putInt("index", index);
    f.setArguments(args);
    return f;
}
Run Code Online (Sandbox Code Playgroud)

然后在方法onCreate或onCreateView上的片段内,您可以检索如下参数:

Bundle args = getArguments();
int index = args.getInt("index", 0);
Run Code Online (Sandbox Code Playgroud)

如果您现在想要从您的片段与您的活动(发送或不发送数据)进行通信,则需要使用接口.你可以这样做的方式在片段之间的通信文档教程中得到了很好的解释.由于所有片段都通过活动在彼此之间进行通信,因此在本教程中,您可以看到如何将数据从实际片段发送到其活动容器,以便在活动上使用此数据或将其发送到您的活动包含的另一个片段.

文档教程:

http://developer.android.com/training/basics/fragments/communicating.html

  • 我认为人们一再提出这个问题的重点是文档中没有很好地解释它. (10认同)

Jor*_*sys 85

将数据发送Activity到aFragment

活动:

Bundle bundle = new Bundle();
String myMessage = "Stackoverflow is cool!";
bundle.putString("message", myMessage );
FragmentClass fragInfo = new FragmentClass();
fragInfo.setArguments(bundle);
transaction.replace(R.id.fragment_single, fragInfo);
transaction.commit();
Run Code Online (Sandbox Code Playgroud)

分段:

读取片段中的值

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
    String myValue = this.getArguments().getString("message");
    ...
    ...
    ...
}
Run Code Online (Sandbox Code Playgroud)

但是如果你想将值从Fragment发送到Activity,请阅读jpardogo的答案,你必须需要接口,更多信息:与其他片段进行通信

  • 如何传递自定义对象?我使用`Parcelable`但是给了我'class cast exception` (2认同)

Sem*_*hor 7

使用库EventBus来传递可能来回包含变量的事件.这是一个很好的解决方案,因为它可以保持您的活动和片段松散耦合

https://github.com/greenrobot/EventBus

  • 我不能说这不是一个好的解决方案,但需要谨慎一点.虽然EventBus非常易于使用,但这也存在危险.如果您开始添加太多信号,松散耦合的性质可能会使跟踪谁在何处以及何处发生不同事件变得非常困难. (4认同)

mah*_*her 7

谢谢 @???????K和Terry ...对我有很大帮助,而且效果很好

从“活动”中,您发送数据的意图是:

Bundle bundle = new Bundle(); 
bundle.putString("edttext", "From Activity"); 
// set Fragmentclass Arguments
Fragmentclass fragobj = new Fragmentclass();
fragobj.setArguments(bundle);
Run Code Online (Sandbox Code Playgroud)

并在Fragment onCreateView方法中:

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
        Bundle savedInstanceState) {
    // get arguments
    String strtext = getArguments().getString("edttext");    
    return inflater.inflate(R.layout.fragment, container, false);
}
Run Code Online (Sandbox Code Playgroud)

参考: 将数据从活动发送到android中的片段


Spi*_*pau 6

对于所有 Kotlin 开发人员:

这是 Android Studio 建议的将数据发送到您的 Fragment 的解决方案(=当您使用 File -> New -> Fragment -> Fragment(Blank) 创建一个 Blank-Fragment 并选中“包含片段工厂方法”时)。

把它放在你的片段中:

class MyFragment: Fragment {

...

    companion object {

            @JvmStatic
            fun newInstance(isMyBoolean: Boolean) = MyFragment().apply {
                arguments = Bundle().apply {
                    putBoolean("REPLACE WITH A STRING CONSTANT", isMyBoolean)
                }
            }
     }
}
Run Code Online (Sandbox Code Playgroud)

.apply在创建对象时设置数据是一个很好的技巧,或者它们在此处声明

this值作为其接收者调用指定的函数 [block]并返回this值。

然后在您的 Activity 或 Fragment 中执行以下操作:

val fragment = MyFragment.newInstance(false)
... // transaction stuff happening here
Run Code Online (Sandbox Code Playgroud)

并阅读片段中的参数,例如:

private var isMyBoolean = false

override fun onAttach(context: Context?) {
    super.onAttach(context)
    arguments?.getBoolean("REPLACE WITH A STRING CONSTANT")?.let {
        isMyBoolean = it
    }
}
Run Code Online (Sandbox Code Playgroud)

要将数据“发送”回您的 Activity,只需在您的 Activity 中定义一个函数并在您的 Fragment 中执行以下操作:

(activity as? YourActivityClass)?.callYourFunctionLikeThis(date) // your function will not be called if your Activity is null or is a different Class
Run Code Online (Sandbox Code Playgroud)

享受 Kotlin 的魔力!