单击EditText时的TimePicker对话框

时间:2015-12-31 00:18:11

标签: java android timepicker

I used this question点击timepicker时获取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);
     }

 }

3 个答案:

答案 0 :(得分:0)

首先在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());
}

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

<强> 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>

答案 1 :(得分:0)

这是代码: 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;
}

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

}

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);
     }

 }




SingleFragmentAcitivity.java
public abstract class SingleFragmentActivity extends FragmentActivity {
    protected abstract Fragment createFragment();
    @Override
    public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_fragment);
    FragmentManager fm = getSupportFragmentManager();
    Fragment fragment = fm.findFragmentById(R.id.fragmentContainer);
    if (fragment == null) {
    fragment = createFragment();
    fm.beginTransaction()
    .add(R.id.fragmentContainer, fragment)
    .commit();
    }
    }
}

Appointactivity.java

package com.example.appointapp;

import android.support.v4.app.Fragment;

public class AppointActivity extends SingleFragmentActivity  {
    @Override
    protected Fragment createFragment() {
    return new AppointFragment();
    }

}

Fragment_main.xml

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

    <Button
        android:id="@+id/new_patient"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
         android:text="@string/new_patient" />

     <Button
        android:id="@+id/new_appoint"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
         android:text="@string/new_appoint"/>

</LinearLayout>

Fragment_appoint.xml

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

<Spinner
    android:id="@+id/Patients_list"
    android:layout_width="117dp"
    android:layout_height="wrap_content" />

<EditText
            android:id="@+id/datea_text"
            android:layout_width="143dp"
            android:layout_height="wrap_content"

            android:hint="@string/datea_text_hint" />

        <EditText
            android:id="@+id/timea_text"
            android:layout_width="141dp"
            android:layout_height="wrap_content"

            android:hint="@string/timea_text_hint" />

        <Button
            android:id="@+id/savea_button"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:gravity="center"
            android:text="@string/savea_button" />

</LinearLayout>

感谢您的帮助

答案 2 :(得分:0)

我在我的片段中使用以下代码解决了这个问题:

chostime.setOnClickListener(new OnClickListener() {

        @Override
        public void onClick(View v) {
            // TODO Auto-generated method stub
            Calendar mcurrentTime = Calendar.getInstance();
            int hour = mcurrentTime.get(Calendar.HOUR_OF_DAY);
            int minute = mcurrentTime.get(Calendar.MINUTE);
            TimePickerDialog mTimePicker;
            mTimePicker = new TimePickerDialog(getActivity(), new TimePickerDialog.OnTimeSetListener() {
                @Override
                public void onTimeSet(TimePicker timePicker, int selectedHour, int selectedMinute) {
                    chostime.setText( selectedHour + ":" + selectedMinute);
                }
            }, hour, minute, true);//Yes 24 hour time
            mTimePicker.setTitle("Select Time");
            mTimePicker.show();

        }
    });

谢谢