在同一个Activity中的Fragments之间传递数据

Sou*_*ane 7 android android-fragments

我正在一个项目中工作,该项目包含许多片段的活动.现在我需要在这些片段之间共享一些数据(整数,字符串,arraylist).

我第一次使用静态字段,但我认为这是一个糟糕的方式然后我找到了这个解决方案.

但在我的情况下,没有按钮可以点击我只需要在片段之间导航是否有任何简单的方法来在片段之间共享数据

ada*_*aRi 6

我认为最适合您的解决方案是将变量放在主活动中并从片段中访问它们.我的意思是,如果你必须在所有片段中做同样的事情,你可以在活动中编写代码,然后调用你需要的方法.

您需要使用接口来实现此目的

public interface DataCommunication {
    public String getMyVariableX();
    public void setMyVariableX(String x);
    public int getMyVariableY();
    public void setMyVariableY(int y);
}
Run Code Online (Sandbox Code Playgroud)

然后,在您的活动中实施它

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;
    }

    ...
Run Code Online (Sandbox Code Playgroud)

然后,将活动附加到所有片段中:

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");
        }
    }

    ...
Run Code Online (Sandbox Code Playgroud)

最后,当你需要在片段中使用变量时,只需使用你创建的get和se方法

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


Bla*_*rai 6

最简单的方法是使用Bundle. 你做这样的事情:

片段A:

Bundle b = new Bundle();
b.putString("Key", "YourValue");
b.putInt("YourKey", 1);

FragmentB fragB = new FragmentB();
fragB.setArguments(b); 
getFragmentManager().beginTransaction().replace(R.id.your_container, fragB);
Run Code Online (Sandbox Code Playgroud)

片段B:

Bundle b = this.getArguments();
if(b != null){
   int i = b.getInt("YourKey");
   String s =b.getString("Key");
}
Run Code Online (Sandbox Code Playgroud)

这是我发现的将数据从一个片段发送到另一个片段的最简单方法。希望它可以帮助某人。


小智 3

您有一些选择:

选项1:如果需要在fragment之间共享信息,可以使用SharedPreferences来存储信息。这是一个例子:

SharedPreferences settings = context.getSharedPreferences("Preferences", Context.MODE_PRIVATE);
    SharedPreferences.Editor editor = settings.edit();
    editor.putString("string1", var);
    editor.putBoolean("bool1", var);
    ...
    editor.commit();
Run Code Online (Sandbox Code Playgroud)

选项2:如果您已经实例化了一个fragment,则可以创建一个set方法来在fragment中存储某种信息。例如,如果你想传递一个字符串数组,你可以在片段中创建一个数组变量(使用setter方法)。稍后,当您实例化该片段时,可以使用 setter 方法将此数组传递给该片段。