如何将一些数据转移到另一个片段同样,它是做了额外的意图?


当前回答

这是你使用bundle的方式:

Bundle b = new Bundle();
b.putInt("id", id);
Fragment frag= new Fragment();
frag.setArguments(b);

从bundle中检索值:

 bundle = getArguments();
 if (bundle != null) {
    id = bundle.getInt("id");
 }

其他回答

使用Bundle。这里有一个例子:

Fragment fragment = new Fragment();
Bundle bundle = new Bundle();
bundle.putInt(key, value);
fragment.setArguments(bundle);

Bundle为许多数据类型提供了方法。看到这个

然后在你的片段,检索数据(例如在onCreate()方法):

Bundle bundle = this.getArguments();
if (bundle != null) {
        int myInt = bundle.getInt(key, defaultValue);
}

只是扩展一下前面的答案——它可以帮助到一些人。如果你的getArguments()返回null,把它放在onCreate()方法,而不是你的片段的构造函数:

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    int index = getArguments().getInt("index");
}

为了进一步扩展前面的答案,就像Ankit说的,对于复杂的对象,你需要实现Serializable。例如,对于简单对象:

public class MyClass implements Serializable {
    private static final long serialVersionUID = -2163051469151804394L;
    private int id;
    private String created;
}

在你的FromFragment中:

Bundle args = new Bundle();
args.putSerializable(TAG_MY_CLASS, myClass);
Fragment toFragment = new ToFragment();
toFragment.setArguments(args);
getFragmentManager()
    .beginTransaction()
    .replace(R.id.body, toFragment, TAG_TO_FRAGMENT)
    .addToBackStack(TAG_TO_FRAGMENT).commit();

在你的ToFragment:

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
            Bundle savedInstanceState) {

    Bundle args = getArguments();
    MyClass myClass = (MyClass) args
        .getSerializable(TAG_MY_CLASS);

使用片段传递数据的完整代码

Fragment fragment = new Fragment(); // replace your custom fragment class 
Bundle bundle = new Bundle();
FragmentTransaction fragmentTransaction = getSupportFragmentManager().beginTransaction();
                bundle.putString("key","value"); // use as per your need
                fragment.setArguments(bundle);
                fragmentTransaction.addToBackStack(null);
                fragmentTransaction.replace(viewID,fragment);
                fragmentTransaction.commit();

在自定义片段类中

Bundle mBundle = new Bundle();
mBundle = getArguments();
mBundle.getString(key);  // key must be same which was given in first fragment

getArguments()返回null因为“它没有得到任何东西”

试试这段代码来处理这种情况

if(getArguments()!=null)
{
int myInt = getArguments().getInt(key, defaultValue);
}