简体   繁体   English

将int值从Activity片段传递到另一个Fragment

[英]Passing an int value from an Activity Fragment to another Fragment

I need to pass an int value from an activity fragment to another fragment. 我需要将一个活动片段的int值传递给另一个片段。 This data will be then set to be in a switch case, which will decide on which android layout file will attach to the fragment. 然后,将这些数据设置为处于切换状态,这将决定将哪个Android布局文件附加到片段。

This is the code from the base activity and on the fragment that sets the value to be passed: 这是来自基础活动和片段上的代码,用于设置要传递的值:

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

btw, I also tried to put the above code on the onCreate and onCreateView method of the fragment but still the same output. 顺便说一句,我也试图将上面的代码放在片段的onCreate和onCreateView方法上,但是仍然是相同的输出。 then after setting the fragment and the bundle, i switch to the other activity and here is the code that will get and use the int value: 然后在设置了片段和包之后,我切换到另一个活动,这是将获取并使用int值的代码:

Bundle bundle = this.getArguments();
int myInt = bundle.getInt(key, defaultValue);

also tried 也尝试过

savedInstanceState = this.getArguments();
int type = savedInstanceState.getInt(key, defaultValue);

when from the base activity, the error is Null Pointer Exception, and when from the 1st fragment, the error is Resource not found. 从基本活动中,错误为Null Pointer Exception;从第一个片段中,错误为Resource not found。

05-12 14:50:47.732: E/ERRORSKI(814): java.lang.NullPointerException
05-12 14:41:38.542: E/ERRORSKI(798): android.content.res.Resources$NotFoundException: String resource ID #0x1

Thank you. 谢谢。

Creating a fragment using the default constructor generally isn't the way to go. 使用默认构造函数创建片段通常不是可行的方法。 Here is an example of what you could better be doing for creating a new instance of your fragment and passing an integer with it. 这是一个示例,您可以更好地创建片段的新实例并为其传递整数。

Place this code in your fragment that will be created. 将此代码放在将要创建的片段中。

public class ExampleFragment {
    public static ExampleFragment newInstance(int exampleInt) {
        ExampleFragment fragment = new ExampleFragment();

        Bundle args = new Bundle();
        args.putInt("exampleInt", exampleInt);
        fragment.setArguments(args);

        return fragment;
    }
}

Use this in your activity to create a new fragment. 在您的活动中使用它来创建一个新片段。

Fragment exampleFragment = ExampleFragment.newInstance(exampleInt);

And later in your fragment, use something like this to get your integer. 然后在您的片段中,使用类似以下的方法获取您的整数。

getArguments().getInt("exampleInt", -1);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM