天天看點

Fragment強烈要求構造方法為空

在使用Fragment的時候,常常需要傳遞參數,一般想法是直接在構造方法中傳遞參數,但是查閱官方文檔發現:

Fragment ()

Default constructor. Every fragment must have an empty constructor, so it can be instantiated when restoring its activity’s state. It is strongly recommended that subclasses do not have other constructors with parameters, since these constructors will not be called when the fragment is re-instantiated; instead, arguments can be supplied by the caller with setArguments(Bundle) and later retrieved by the Fragment with getArguments().

這段話的意思是Fragment的構造方法不能帶參數,如果要傳遞參數,可以用setArguments(Bundle)傳遞Bundle對象,然後在Fragment用getArguments(Bundle)擷取Bundle對象,進而擷取參數。

比如:

在我們的Fragment中添加如下方法:

public static MyFragment newInstance(String param1, String param2) { MyFragment fragment = new MyFragment(); Bundle args = new Bundle(); args.putString("Param1", param1); args.putString("Param1", param2); fragment.setArguments(args); return fragment;

需要傳遞參數建立MyFragment的時候就使用這種方法,然後在MyFragment中使用 getArguments().getString(”Param1”) 擷取參數。

關于為什麼不能使用有參數的構造方法,可以看一下這一篇:

淺析Fragment為什麼需要空的構造方法

繼續閱讀