java 访问 Fragment 中的活动变量

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/42353456/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-11-03 06:33:50  来源:igfitidea点击:

Access Activity Variables in Fragment

javaandroidandroid-fragmentsandroid-activityandroid-fragmentactivity

提问by Jude Fernandes

If i have an Activity A which extends a base activity BA then i am able to safely access any variable in activity BA from activity A.What i am using now contains an activity A which includes a fragment F. Now from this fragment i want to access all variables of A in the same manner,just like i did above and if not is there a safe way of doing it other than making it available through public methods.

如果我有一个扩展基本活动 BA 的活动 A,那么我可以从活动 A 安全地访问活动 BA 中的任何变量。以相同的方式访问 A 的所有变量,就像我在上面所做的那样,如果没有,除了通过公共方法使其可用之外,还有其他安全的方法可以做到这一点。

Or is there a way i can copy over the variables in the base activity to a base fragment so its available in all activities and fragments.

或者有没有一种方法可以将基础活动中的变量复制到基础片段中,以便它在所有活动和片段中可用。

回答by GVillani82

A good way for implementing it is to use an interface, as the official documentation suggests.

正如官方文档所建议的那样,实现它的一个好方法是使用接口。

To allow a Fragment to communicate up to its Activity, you can define an interface in the Fragment class and implement it within the Activity.

要允许 Fragment 与其 Activity 通信,您可以在 Fragment 类中定义一个接口并在 Activity 中实现它。

So, basically inside your fragment you define an interface like this:

所以,基本上在你的片段中你定义了一个这样的接口:

public interface MyListener {
     public void onAction();
}

and define (still in the fragment) a field of type MyListener

并定义(仍在片段中)一个类型的字段 MyListener

MyListener mCallback;

Then you can set this listener using the onAttach(Activity)method:

然后您可以使用以下onAttach(Activity)方法设置此侦听器:

mCallback = (MyListener) activity;

Now, each time you want call from your fragment a method in the activity you can use the callback:

现在,每次您想从片段调用活动中的方法时,您都可以使用回调:

mCallback.onAction();

Of course, your Activity need to implement the interface, otherwise you will get an exception while casting your activity to MyListener.

当然,您的 Activity 需要实现该接口,否则将您的 Activity 投射到 MyListener 时会出现异常。

So, just do:

所以,只要这样做:

public class MyActivity extends Activity implements MyFragment.MyListener {
    @Override
    public void onAction() {
        // some stuff
    }
}

For more details take a look at the documentationabout communication between fragments

有关更多详细信息,请查看有关片段之间通信的文档

回答by Atef Hares

If VARIABLE_NAMEis a variable in you activity ACTIVITY_NAMEand can be accessed from outside Activity ACTIVITY_NAME

IfVARIABLE_NAME是您活动中的变量,ACTIVITY_NAME可以从活动外部访问ACTIVITY_NAME

Then use this code:

然后使用此代码:

((ACTIVITY_NAME)this.getActivity()).VARIABLE_NAME //this refers to your fragment