在同一活动中的片段之间传递数据 [英] Passing data between Fragments in the same Activity
问题描述
我正在一个带有许多片段的Activity的项目中工作.现在,我需要在这些片段之间共享一些数据(整数,字符串,数组列表).
Am working in a project with an Activity that host many fragments. Now I need to share some data (integers, strings, arraylist) between these fragments.
我第一次使用静态字段,但我认为这是一种不好的方法然后我找到了此解决方案.
First time i used static fields but I think it's a bad way then I found this solution.
但是在我的情况下,没有按钮可以单击,我只能在片段之间导航是否有任何简单的方法可以使片段之间共享数据
but in my case there is no button to click i have just to navigate between fragments is there any simple way to make sharing data between fragments
推荐答案
我认为,最适合您的解决方案是将变量包含在主活动中并从片段中访问它们.我的意思是,如果必须在所有片段中都做同样的事情,则可以在活动中编写代码,然后仅调用所需的方法.
I think the best solution for you is to have the variables inside the main activity and access them from fragments. I mean, if you have to do THE SAME in all fragments, you can write the code inside the activity and just call the method you need.
您需要为此使用一个界面
You need to use an interface for this purpose
public interface DataCommunication {
public String getMyVariableX();
public void setMyVariableX(String x);
public int getMyVariableY();
public void setMyVariableY(int y);
}
然后,在您的活动中实施
Then, implement it inside your activity
public class MainActivity extends Activity implements DataCommunication {
private String x;
private int y;
@Override
protected void onCreate(Bundle savedInstanceState) {
...
}
...
@Override
public String getMyVariableX(){
return x;
}
@Override
public void setMyVariableX(String x){
//do whatever or just set
this.x = x;
}
@Override
public int getMyVariableY(){
return y;
}
@Override
public void setMyVariableY(int y){
//do whatever or just set
this.y = y;
}
...
然后,将活动附加到所有片段中:
Then, attach the activity in ALL your fragments:
public class Fragment_1 extends Fragment{
DataCommunication mCallback;
@Override
public void onAttach(Context context) {
super.onAttach(context);
// This makes sure that the container activity has implemented
// the callback interface. If not, it throws an exception
try {
mCallback = (DataCommunication) context;
} catch (ClassCastException e) {
throw new ClassCastException(context.toString()
+ " must implement DataCommunication");
}
}
...
最后,当您需要在片段中使用变量时,只需使用已创建的get和se方法
And finally, when you need to use a variable inside a fragment, just use get and se methods you've created
https://developer.android.com/training/basics/fragments/communicating.html
这篇关于在同一活动中的片段之间传递数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!