背景:在一次release打包中發現lint報以下錯誤:
Error: Avoid non-default constructors in fragments: use a default constructor plus Fragment#setArguments(Bundle) instead [ValidFragment]
根據后面的log提示是由于重載了fragment的構造函數,雖然緊接著lint提供了一個修改build script解決該問題的方法,不過這種方法對于有“追求”的程序員,是不會這么解決掉的。如何解決呢,google以下吧。
Avoid non-default constructors in fragments: use a default constructor plus Fragment報錯的解決方法
以上鏈接文章其實已經給出了解決方法,沒其他需要補充的了。
但是為什么需要這樣做,上文沒有提到,我只猜測下了:
文中提到這么個原因:
其原因是你重載了fragment的構造方法,但是在一些情況下,如屏幕翻轉時,fragment被重新創建,就可能會造成數據丟失。
我的理解是,當fragment重建時,重載的構造方法的參數會丟失。但為什么通過newInstance就不會丟失呢?
public static CustomCommonEditDialog newInstance(String content, int type) {CustomCommonEditDialog newFragment = new CustomCommonEditDialog();Bundle bundle = new Bundle();bundle.putString("content", content);bundle.putInt("type", type);newFragment.setArguments(bundle);return newFragment;}
我猜測是bundle的數據是在fragment重建過程中是不會丟失的。(各位有經驗的android開發者不要嘲笑我,不太了解fragment.setArguments這個接口的作用,對于一個只有三個月開發經驗的android程序員,還有太多東西要了解,這個先放一放了)
補充用到的代碼:
//在fragment onCreate接口中獲取上面的參數
Bundle args = getArguments();
if (args != null) {content = args.getString("content");type = args.getInt("type");
}
調用:
CustomCommonEditDialog dialog = CustomCommonEditDialog.newInstance("String", 1);
附錯誤log(log里其實已經寫的很明確了,E文很重要啊):
CustomCommonEditDialog.java:47: Error: Avoid non-default constructors in fragments: use a default constructor plus Fragment#setArguments(Bundle) instead [ValidFragment]public CustomCommonEditDialog(String content, int type) {~~~~~~~~~~~~~~~~~~~~~~Explanation for issues of type "ValidFragment":From the Fragment documentation:Every fragment must have an empty constructor, so it can be instantiatedwhen restoring its activity's state. It is strongly recommended thatsubclasses do not have other constructors with parameters, since theseconstructors 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().http://developer.android.com/reference/android/app/Fragment.html#Fragment()1 errors, 0 warningsFAILEDFAILURE: Build failed with an exception.* What went wrong:
Execution failed for task ':vassistant:lintVitalRelease'.
> Lint found fatal while assembling a release target.To proceed, either fix the issues identified by lint, or modify your build script as follows:...android {lintOptions {checkReleaseBuilds false// Or, if you prefer, you can continue to check for errors in release builds,// but continue the build even when errors are found:abortOnError false}}...