单击timepicker时,通过I used this question获取editext
请注意,我将代码放在一个片段中。
我更改了以下内容:

在settime.java中添加了上下文ctx;

在线上:

SetTime fromTime = new SetTime(chostime,this);


告诉我:未定义构造函数SetTime(editText, AppointFragment)

我尝试将其更改为:

SetTime fromTime = new SetTime(chostime,getActivity());


尝试运行应用程序时,出现以下错误


  12-30 18:03:55.120:E / AndroidRuntime(1376):java.lang.NullPointerException


这是代码:

AppointFragment.java

package com.example.appointapp;

import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Locale;

import android.app.DatePickerDialog;
import android.app.DatePickerDialog.OnDateSetListener;
import android.os.Bundle;
import android.support.v4.app.DialogFragment;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.DatePicker;
import android.widget.EditText;

public class AppointFragment extends Fragment{

    private static final String TAG = "AppoinFragment";
    EditText chosdate, chostime;

    private Appointment mappointment;
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        mappointment= new Appointment();
        }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup parent, Bundle savedInstanceState){
    View v = inflater.inflate(R.layout.fragment_appoint, parent, false);
    chosdate = (EditText)v.findViewById(R.id.datea_text);
    chostime = (EditText)v.findViewById(R.id.timea_text);
    SetTime fromTime = new SetTime(chostime,this);
    chosdate.setOnFocusChangeListener(new View.OnFocusChangeListener() {
        @Override
        public void onFocusChange(View v, boolean hasFocus) {
            if (hasFocus) {
                DialogFragment datePickerFragment = new DatePickerFragment() {
                    @Override
                    public void onDateSet(DatePicker view, int year, int month, int day) {
                        Log.d(TAG, "onDateSet");
                        Calendar c = Calendar.getInstance();
                        c.set(year, month, day);

                        String myFormat = "dd/MM/yy";
                        SimpleDateFormat sdf = new SimpleDateFormat(myFormat, Locale.US);

                        chosdate.setText(sdf.format(c.getTime()));

                        chosdate.requestFocus();
                    }
                };
                datePickerFragment.show(getActivity().getSupportFragmentManager(), "datePicker");
            }
        }
    });


    return v;
}
}


SetTime.java

package com.example.appointapp;

import java.util.Calendar;

import android.app.TimePickerDialog;
import android.app.TimePickerDialog.OnTimeSetListener;
import android.content.Context;
import android.view.View;
import android.view.View.OnFocusChangeListener;
import android.widget.EditText;
import android.widget.TimePicker;


class SetTime implements OnFocusChangeListener, OnTimeSetListener {

    private EditText editText;
    private Calendar myCalendar;
    Context ctx;

    public SetTime(EditText editText, Context ctx){
        this.editText = editText;
        this.editText.setOnFocusChangeListener(this);
        this.myCalendar = Calendar.getInstance();

    }

     @Override
     public void onFocusChange(View v, boolean hasFocus) {

         if(hasFocus){
             int hour = myCalendar.get(Calendar.HOUR_OF_DAY);
             int minute = myCalendar.get(Calendar.MINUTE);
             new TimePickerDialog(ctx, this, hour, minute, true).show();
         }
     }

     @Override
     public void onTimeSet(TimePicker view, int hourOfDay, int minute) {

         this.editText.setText( hourOfDay + ":" + minute);
     }

 }

最佳答案

首先在onActivityCreated()中覆盖AppointFragment,然后使用getActivity()创建SetTime对象。

private SetTime fromTime;
private EditText chosdate, chostime;

...

@Override
public void onActivityCreated(@Nullable Bundle savedInstanceState)
{
    super.onActivityCreated(savedInstanceState);
    fromTime = new SetTime(chostime,getActivity());
}




下面是使用片段设置时间的完整代码。您也可以使用相同的方法来设置日期。

MainActivity.java

public class MainActivity extends AppCompatActivity
{

    @Override
    protected void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        // Create a new Fragment to be placed in the activity layout
        ChildFragment firstFragment = new ChildFragment();

        // In case this activity was started with special instructions from an
        // Intent, pass the Intent's extras to the fragment as arguments
        //firstFragment.setArguments(getIntent().getExtras());

        // Add the fragment to the 'fragment_container' FrameLayout
        getSupportFragmentManager().beginTransaction()
                .add(R.id.frameLayout, firstFragment).commit();

    }


ChildFragment.java(用于显示EditTexts)

public class ChildFragment extends Fragment implements View.OnClickListener, TimePickerFragment.Callback
{
    private EditText editText;

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState)
    {
        View view  = inflater.inflate(R.layout.child_fragment, null, false);
        editText = (EditText) view.findViewById(R.id.time_edit_text);
        editText.setOnClickListener(this);
        return view;
    }

    @Override
    public void onClick(View view)
    {
        if(view == editText)
        {
            TimePickerFragment dialog = new TimePickerFragment();
            dialog.setTargetFragment(this, 1); //request code
            dialog.show(getFragmentManager(),"dialog");
        }
    }

    @Override
    public void onTimeSelected(String time)
    {
        editText.setText(time);
    }
}


TimePickerFragment.java

public class TimePickerFragment extends DialogFragment
        implements TimePickerDialog.OnTimeSetListener {

    public interface Callback
    {
        public void onTimeSelected(String time);
    }
    private Callback timeCallback;

    @Override
    public Dialog onCreateDialog(Bundle savedInstanceState) {
        // Use the current time as the default values for the picker
        final Calendar c = Calendar.getInstance();
        int hour = c.get(Calendar.HOUR_OF_DAY);
        int minute = c.get(Calendar.MINUTE);

        timeCallback = (Callback) getTargetFragment();

        // Create a new instance of TimePickerDialog and return it
        return new TimePickerDialog(getActivity(), this, hour, minute,
                DateFormat.is24HourFormat(getActivity()));
    }

    public void onTimeSet(TimePicker view, int hourOfDay, int minute) {
        // Do something with the time chosen by the user
        timeCallback.onTimeSelected(hourOfDay + ":" + minute + ":00");
    }
}


activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <FrameLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:id="@+id/frameLayout"/>
</RelativeLayout>


child_fragment.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
              android:orientation="vertical"
              android:layout_width="match_parent"
              android:layout_height="match_parent">
<EditText
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:id="@+id/time_edit_text"/>
</LinearLayout>

10-07 12:43