错误:此片段应提供默认构造函数(不带参数的公共构造函数)

时间:2015-04-21 04:31:33

标签: java android android-studio

我的课程扩展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)

4 个答案:

答案 0 :(得分:22)

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

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

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

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 
} 

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

答案 1 :(得分:4)

您需要删除此构造函数

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

您不应将视图引用传递给Fragment。如果要在Activity或其他地方更新EditText,请使用侦听器。

答案 2 :(得分:1)

      public DatePickerFragment() {}

        @Override
        public void onDateSet(DatePicker view, int year, int monthOfYear, int dayOfMonth) {
                dateTime.set(year, monthOfYear, dayOfMonth);
             //   editDate.setText(dateFormatter
             //         .format(dateTime.getTime()));
            Intent intent = new Intent();
            intent.setAction("CUSTOM_INTENT_FOR_SETTING_EDITTEXT");
            Bundle bundle = new Bundle();
            bundle.putString("my_data", dateTime.getTime.toString());
            intent.putExtras(bundle);
            sendBroadcast(intent);
            }




public class SubmitFragment extends Fragment {

    View view;
    EditText editDate;
    String strDate;
    Button btnSubmit;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        view = inflater.inflate(R.layout.fragment_submit, container, false);

        editDate = (EditText) view.findViewById(R.id.editDate);

        btnSend = (Button) view.findViewById(R.id.buttonSend);
        btnSend.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                strDate = editDate.getText().toString();
                Log.v("strDate..... >>>", strDate);

            }
        });

        return view;
    }


        // Our handler for received Intents. This will be called whenever an Intent
        // with an action named "CUSTOM_INTENT_FOR_SETTING_EDITTEXT" is broadcasted.
        private BroadcastReceiver mMessageReceiver = new BroadcastReceiver() {
          @Override
          public void onReceive(Context context, Intent intent) {
            // Get extra data included in the Intent
            String message = intent.getStringExtra("my_data");
            Log.d("receiver", "message: " + message);
        *****// Use this message to set Edittext here...*****
          }
        };


        @Override
        protected void onPause() {
          // Unregister since the activity is about to be closed.
          LocalBroadcastManager.getInstance(getactivity()).unregisterReceiver(mMessageReceiver);
          super.onDestroy();
        }


        @Override
        protected void onResume() {
          // register the receiver here..
       super.onResume(); LocalBroadcastManager.getInstance(getactivity()).registerReceiver(mMessageReceiver,
              new IntentFilter("CUSTOM_INTENT_FOR_SETTING_EDITTEXT"));
        }
}

希望这会有所帮助..我在这里做的正是使用localBroadcast来  做必要的。另一种方法是使用settext的接口 但是关于这种方法的一个错误的事情是当应用程序处于后台时 long,当再次调用oncreateview时它将返回null。

答案 3 :(得分:1)

添加@SuppressLint(“ValidFragment”)

在你上课之前,

公共类DatePickerFragment extends

我希望它可以帮到你