gpt4 book ai didi

java - 错误 : This fragment should provide a default constructor (a public constructor with no arguments)

转载 作者:太空狗 更新时间:2023-10-29 23:02:57 26 4
gpt4 key购买 nike

我的类像这样扩展 DialogFragment:

public class DatePickerFragment extends DialogFragment implements DatePickerDialog.OnDateSetListener {

EditText editDate;
private Calendar dateTime = Calendar.getInstance();
private SimpleDateFormat dateFormatter = new SimpleDateFormat("dd MMMM yyyy");

public DatePickerFragment(EditText editText) {
editDate = editText;
}

@Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
// Use the current date as the default date in the picker
final Calendar c = Calendar.getInstance();
int year = c.get(Calendar.YEAR);
int month = c.get(Calendar.MONTH);
int day = c.get(Calendar.DAY_OF_MONTH);

// Create a new instance of DatePickerDialog and return it
return new DatePickerDialog(getActivity(), this, year, month, day);

}

@Override
public void onDateSet(DatePicker view, int year, int monthOfYear, int dayOfMonth) {
dateTime.set(year, monthOfYear, dayOfMonth);
editDate.setText(dateFormatter
.format(dateTime.getTime()));
}

}

这就是我在 Activity 中使用它的方式:

public void showDatePickerDialog(View v) {
new DatePickerFragment((EditText) v).show(getSupportFragmentManager(), "datePicker");
}

然后这样调用:

    <EditText
android:id="@+id/editDate"
android:onClick="showDatePickerDialog" />

但我总是得到:

Error: This fragment should provide a default constructor (a public constructor with no arguments)

最佳答案

较新版本的 Android SDK 强制您获得一个空的、无参数的构造函数。现在这样做是一个很好的做法。这允许您将实例状态保存到 bundle 中,Android 将重新创建您的 fragment 并调用默认构造函数。

对于这种情况,您有以下解决方案:

首先,创建默认构造函数:

public DatePickerFragment() {}

创建实例并通过setter方法设置EditText:

DatePickerFragment fragment = new DatePickerFragment();
fragment.setEditText(v); // create this setter
fragment.show();

由于 EditText 是可打包的,您还可以设置为参数:

DatePickerFragment fragment = new DatePickerFragment();
Bundle bundle = new Bundle();
bundle.putExtra("EditText", v);
fragment.setArguments(bundle); // setArguments is a method that already exists in fragments.
fragment.show(getSupportFragmentManager(), "DatePicker");

[编辑]按照建议,尝试忽略这些配置 build.gradle 的错误,如下所示:

lintOptions { 
abortOnError false
checkReleaseBuilds false
}

这不会通过在 fragment 中使用非默认构造函数来停止应用程序的构建。

关于java - 错误 : This fragment should provide a default constructor (a public constructor with no arguments),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29762949/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com