Fragment構造函數打包時的踩坑:should provide a default constructor
今晚項目上線完成后,準備打個release的線上apk包,結果令人尷尬的事情出現了,丫的居然編譯失敗了,debug包一直編譯正常啊。android studio報錯:This fragment should provide a default constructor (a public constructor with no arguments),修改后又報新錯誤:Avoid non-default constructors in fragments: use a default constructor plus Fragment#setArguments(Bundle) instead [ValidFragment]。下面就來具體說一下Fragment打包時報的這兩個錯誤原因以及解決方案。
報錯1:
This fragment should provide a default constructor (a public constructor with no arguments)
在打包時出現在這個問題,原因是一定要有一個無參的默認構造函數,如果不寫任何構造函數,其實會默認初始化一個無參的構造函數,這時其實是不會報錯的。但是一旦寫了帶參數的構造方法而沒有重寫無參的構造函數,這時就要打包編譯時提示上邊的警告了。
貼下我當時的一個錯誤或者不合理寫法:
publicclassMyFragment extendsBaseFragment{
????publicMyFragment(Context context) {
????????mContext = context;
????}
????publicstaticMyFragment newInstance(Context context) {
????????returnnewMyFragment (context);
????}
}
為了不讓報這個錯,還是按照官方建議寫一個無參的構造函數,如下:
publicclassMyFragment extendsBaseFragment{
????publicMyFragment() {
????}
????publicstaticMyFragment newInstance(Context context) {
????????mContext = context;
????????returnnewMyFragment ();
????}
}
其實也可以直接把無參的構造函數去掉,系統會默認創建的。
報錯2:
1Avoid non-defaultconstructors in fragments: use a defaultconstructor plus Fragment#setArguments(Bundle) instead [ValidFragment]
在打包時出現這個問題,在類上加一個注解@SuppressLint(“ValidFragment”)可以達到不報錯的目的,但是為避免Fragment中的非默認構造函數,官方還是建議使用默認構造函數加上Fragment#setArguments(Bundle)代替[ValidFragment]。
所以需要修改為如下的形式:
publicclassMyFragment extendsBaseFragment{
????publicMyFragment() {
????????mContext = getActivity();
????}
????publicstaticMyFragment newInstance(String tag) {
????????MyFragment myFragment = newMyFragment();
????????Bundle bundle = newBundle();
????????bundle.putString("tag",tag);
????????myFragment.setArguments(bundle);
????????returnmyFragment;
????}
}
按照上邊的建議來修改Fragment的構造函數和靜態工廠方法newInstance()來獲取實例就可以避免在正式打包時報上邊的兩個錯誤了。
其實,還有一種方法也能達到不報錯的目的,就是直接在?build.gradle 配置文件中的android{ ··· }節點內添加配置禁止在正式打包時檢測這個錯誤就可以了,添加格式如下:
android {
????··· ···
????buildTypes {
????????release {
????????????··· ···
????????}
????????debug {
????????????··· ···
????????}
????}
????lintOptions {
????????abortOnError false
????????checkReleaseBuilds false
????}
}
但是個人建議,應該盡量還是按照Google官方的建議解決方案來處理會比較好些。當然也可以視具體情況而定。