使用SherlockFragment实现日期和时间选择器对话框

时间:2014-02-14 07:37:39

标签: android actionbarsherlock

我正在编写一个程序,我想让用户使用点击按钮选择日期和时间,然后显示选定的日期和时间到TextViews。

早些时候,我在Activity中做了同样的事情,但是没有足够的关于如何使用SherlockFragment做到这一点。

MainActivity.java:

public class MainActivity extends SherlockFragmentActivity implements PickTime{
    // Declare Variables    
    private FragmentTabHost mTabHost;

    FragmentTab1 newFragment;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        // Set the view from main_fragment.xml
        setContentView(R.layout.main_fragment);

        newFragment = new FragmentTab1();

        // Locate android.R.id.tabhost in main_fragment.xml
        mTabHost = (FragmentTabHost) findViewById(android.R.id.tabhost);

        // Create the tabs in main_fragment.xml
        mTabHost.setup(this, getSupportFragmentManager(), R.id.tabcontent);

        // Create Tab1 with a custom image in res folder
        mTabHost.addTab(mTabHost.newTabSpec("tab1").setIndicator("", getResources().getDrawable(R.drawable.tab1)),
                FragmentTab1.class, null);

        // Create Tab2
        mTabHost.addTab(mTabHost.newTabSpec("tab2").setIndicator("Tab2"),
                FragmentTab2.class, null);

        // Create Tab3
        mTabHost.addTab(mTabHost.newTabSpec("tab3").setIndicator("Tab3"),
                FragmentTab3.class, null);
    }

     @Override
        public void returnTime(String value) {
         newFragment.setTimet(value);   

        }
}

FragmentTab1.java:

public class FragmentTab1 extends SherlockFragment {

    Button buttonDate;  // change date
    Button buttonTime;  // change time

    TextView textDate;  // default current date
    TextView textTime;  // default current time
    TimePickerFragment newFragment;
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
            Bundle savedInstanceState) {
        View rootView = inflater.inflate(R.layout.fragmenttab1, container, false);

        buttonDate = (Button) rootView.findViewById(R.id.btnDate);
        buttonTime = (Button) rootView.findViewById(R.id.btnTime);        

        textDate = (TextView) rootView.findViewById(R.id.txtDate);
        textTime = (TextView) rootView.findViewById(R.id.txtTime);

        buttonTime.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View arg0) {
                // TODO Auto-generated method stub
                  newFragment = new TimePickerFragment();
                  newFragment.show(getSherlockActivity().getSupportFragmentManager(), "timePicker");
            }
        });


        return rootView;
    }

   public void setTimet(String text)
   {
       try {
           textTime.setText(text);
           }catch(Exception e) {
              e.printStackTrace();
              Log.i("Log", e.getMessage()+"Error!");
           }
   }

}

TimePickerFragment.java:

public class TimePickerFragment  extends DialogFragment
implements TimePickerDialog.OnTimeSetListener{

      public interface PickTime
        {
            public void returnTime(String value);

        }

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

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

        if(mCallback!=null)
        {
            StringBuilder sb = new StringBuilder();
            sb.append(hourOfDay);
            sb.append(":");
            sb.append(minute);
            mCallback.returnTime(sb.toString());
        }
    }

}

日志:

   02-14 04:10:20.173: W/System.err(1744): java.lang.NullPointerException
02-14 04:10:20.263: W/System.err(1744):     at com.example.datetimeabs.FragmentTab1.setTimet(FragmentTab1.java:51)
02-14 04:10:20.263: W/System.err(1744):     at com.example.datetimeabs.MainActivity.returnTime(MainActivity.java:44)
02-14 04:10:20.263: W/System.err(1744):     at com.example.datetimeabs.TimePickerFragment.onTimeSet(TimePickerFragment.java:44)
02-14 04:10:20.263: W/System.err(1744):     at android.app.TimePickerDialog.tryNotifyTimeSet(TimePickerDialog.java:130)
02-14 04:10:20.273: W/System.err(1744):     at android.app.TimePickerDialog.onStop(TimePickerDialog.java:137)
02-14 04:10:20.273: W/System.err(1744):     at android.app.Dialog.dismissDialog(Dialog.java:336)
02-14 04:10:20.273: W/System.err(1744):     at android.app.Dialog.dismiss(Dialog.java:312)
02-14 04:10:20.273: W/System.err(1744):     at com.android.internal.app.AlertController$ButtonHandler.handleMessage(AlertController.java:170)
02-14 04:10:20.273: W/System.err(1744):     at android.os.Handler.dispatchMessage(Handler.java:102)
02-14 04:10:20.273: W/System.err(1744):     at android.os.Looper.loop(Looper.java:136)
02-14 04:10:20.273: W/System.err(1744):     at android.app.ActivityThread.main(ActivityThread.java:5017)
02-14 04:10:20.283: W/System.err(1744):     at java.lang.reflect.Method.invokeNative(Native Method)
02-14 04:10:20.283: W/System.err(1744):     at java.lang.reflect.Method.invoke(Method.java:515)
02-14 04:10:20.283: W/System.err(1744):     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:779)
02-14 04:10:20.283: W/System.err(1744):     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:595)
02-14 04:10:20.283: W/System.err(1744):     at dalvik.system.NativeStart.main(Native Method)
02-14 04:10:20.283: I/Log(1744): nullError!

1 个答案:

答案 0 :(得分:2)

您需要使用interface作为活动的回调。然后将值传递给片段。

与DatePicker相同。根据您的需要进行修改

public class FragmentTab1 extends SherlockFragment implements OnClickListener {

    Button buttonDate;  // change date
    Button buttonTime;  // change time

    TextView textDate;  // default current date
    TextView textTime;  // default current time
    TimePickerFragment newFragment;
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
            Bundle savedInstanceState) {
        View rootView = inflater.inflate(R.layout.fragmenttab1, container, false);

        buttonDate = (Button) rootView.findViewById(R.id.button1);
        buttonTime = (Button) rootView.findViewById(R.id.button2);
        buttonTime.setOnClickListener(this);

        textDate = (TextView) rootView.findViewById(R.id.textView1);
        textTime = (TextView) rootView.findViewById(R.id.textView2);

        return rootView;
    }
    @Override
    public void onClick(View v) {
        // TODO Auto-generated method stub
        switch(v.getId())
        {
        case R.id.button1 :

            break;
        case R.id.button2:
            newFragment = new TimePickerFragment();
            newFragment.show(getSherlockActivity().getSupportFragmentManager(), "timePicker");
        break;
        }

    }
   public void setTimet(String text)
   {
       textDate.setText(text);
   }

}

TimerPickerFragment

public class TimePickerFragment extends DialogFragment
implements TimePickerDialog.OnTimeSetListener {
    public interface PickTime
    {
        public void returnTime(String value);

    }

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

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

    if(mCallback!=null)
    {
        StringBuilder sb = new StringBuilder();
        sb.append(hourOfDay);
        sb.append(":");
        sb.append(minute);
        mCallback.returnTime(sb.toString());
    }
}
}

活动

public class MainActivity extends SherlockFragmentActivity implements PickTime{

    FragmentTab1 newFragment;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        newFragment = new FragmentTab1();
        FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
        transaction.replace(R.id.content, newFragment);
        transaction.addToBackStack(null);

        transaction.commit();

    }

    @Override
    public void returnTime(String value) {
     newFragment.setTimet(value);   

    }


}

对齐

enter image description here enter image description here