android - 如何解决此 fragment "non-default constructor"错误?

标签 android android-fragments

我继承了这个 Android 应用程序。当我尝试构建签名的 APK 时,我收到一条错误消息,内容为 Error:(31) Error: Avoid non-default constructors in fragments: use a default constructor plus Fragment#setArguments(Bundle) instead [ValidFragment]

它指向这段代码:

public class BasicInfoFragment extends BasePassportFragment implements LocationEditText.LocationEditTextListener {

    private User user;
    private Templates templates;

    public BasicInfoFragment() {
        super(false);
    }

    public BasicInfoFragment(User user) {
        super(false);
        this.user = user;
    }

    public BasicInfoFragment(User user, Templates templates) {
        super(false);
        this.user = user;
        this.templates = templates;
    }

   ...

}

错误指向第二个和第三个方法,public BasicInfoFragment(User user)public BasicInfoFragment(User user, Templates templates) 所以我很困惑为什么 public BasicInfoFragment() 可以,但其他两个不行?

最佳答案

I am confused why public BasicInfoFragment() is okay but the other two are not?

当 Activity 作为配置更改(例如,屏幕旋转)的一部分被销毁并重新创建时,Android 会自动销毁并重新创建由旧 Activity 实例管理的 fragment 。为此,它将使用默认构造函数,而不是其他两个构造函数中的任何一个。

此外,当您在后台时您的应用程序进程终止,并且用户返回到您的应用程序(例如,最近的任务列表),Android 将创建您的 Activity 的全新实例......以及所有它的 fragment 。它将再次使用默认构造函数。

使用其他构造函数的风险在于,在上述任一事件中,传递给这些构造函数的任何对象都容易丢失。 Lint 正在引导您摆脱那些构造函数并使用工厂模式(例如,静态 newInstance() 方法),其中数据通过 setArguments() 提供给 fragment 。方法。这附加了一个 Bundle ,可由 fragment 实例通过 getArguments() 检索.那Bundle自动成为已保存实例状态的一部分,将通过上述任一事件保留。

TL;DR:其他公共(public)构造函数代表了一种足够强烈的“代码味道”,Lint 如今会冲你大喊大叫

关于android - 如何解决此 fragment "non-default constructor"错误?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25370712/

相关文章:

android - adb shell dumpsys meminfo - 其输出的每个单元格的含义是什么?

android - 在 Android 上构建兼容性 PreferenceFragment

android - 使用 listactivity 扩展 Fragments

android - 如何为android中 fragment 中的按钮设置onclick监听器

android - 跨多个 fragment 重用回调接口(interface)

android - 在 Navigation Drawer 的每个 fragment 中实现不同的 Action Bar 项目

android - Android应用:创建静音按钮

android - 如何在 android pie(9) 设备中获取当前的 wifi 连接名称?

android - 是否可以在 android studio 的 java 文件中使用 scala 对象?

java - 如何在achartengine中设置饼图切片的边框颜色?