簡體   English   中英

將int值從Activity片段傳遞到另一個Fragment

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

我需要將一個活動片段的int值傳遞給另一個片段。 然后,將這些數據設置為處於切換狀態,這將決定將哪個Android布局文件附加到片段。

這是來自基礎活動和片段上的代碼,用於設置要傳遞的值:

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

順便說一句,我也試圖將上面的代碼放在片段的onCreate和onCreateView方法上,但是仍然是相同的輸出。 然后在設置了片段和包之后,我切換到另一個活動,這是將獲取並使用int值的代碼:

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

也嘗試過

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

從基本活動中,錯誤為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

謝謝。

使用默認構造函數創建片段通常不是可行的方法。 這是一個示例,您可以更好地創建片段的新實例並為其傳遞整數。

將此代碼放在將要創建的片段中。

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

在您的活動中使用它來創建一個新片段。

Fragment exampleFragment = ExampleFragment.newInstance(exampleInt);

然后在您的片段中,使用類似以下的方法獲取您的整數。

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM