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


当前回答

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

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

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

其他回答

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

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

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

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

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

使用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);
}

如果你正在使用kotlin,那么你可以传递bundle as

val fragment = YourFragment()
val bundle = Bundle().apply {
    putInt("someInt", 5)
    putString("someString", "Hello")
}
fragment.arguments = bundle

在YourFragment的onCreate中获取这些值

this.arguments?.let {
    val someInt    = it.getInt("someInt", someDefaultInt)
    val someString = it.getString("someString", someDefaultString)
}

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

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