片段活动的简单时间戳

时间:2013-12-27 03:27:40

标签: java android android-fragments android-timepicker

我正在尝试从片段中的timepicker启动edittext

Buffet_offerings_breakfast_menu2.java

public class Buffet_offerings_breakfast_menu2 extends Fragment implements PickTime{

    RadioGroup radioGroup;


    EditText ed1,ed2;
    boolean flag =false;
    TimePickerFragment newFragment;


    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
            Bundle savedInstanceState) {
        // TODO Auto-generated method stub

        final View view=inflater.inflate(R.layout.buffet_offerings_breakfast_menu2, container, false);

        ed1 = (EditText) view.findViewById(R.id.from_lunch_edit_text_id);
        ed2 = (EditText) view.findViewById(R.id.to_lunch_edit_text_id);

        radioGroup = (RadioGroup) view.findViewById(R.id.radioGroup1);        

        newFragment = new TimePickerFragment();

        ed1.setOnFocusChangeListener(new OnFocusChangeListener() {
            @Override
            public void onFocusChange(View v, boolean hasFocus) {
                if(hasFocus){
                  flag =false;
                  newFragment.show(getFragmentManager(), "timePicker");
                }
               }
            });

        ed2.setOnFocusChangeListener(new OnFocusChangeListener() {
            @Override
            public void onFocusChange(View v, boolean hasFocus) {
                if(hasFocus){
                  flag =true;
                  newFragment.show(getFragmentManager(), "timePicker");
                }
               }
            });
        radioGroup.setOnCheckedChangeListener(new OnCheckedChangeListener(){  
          public void onCheckedChanged(RadioGroup group, int checkedId) {
             // checkedId is the RadioButton selected
                   if(checkedId == R.id.SelectDaysRG_ID)
                   {
                      view.findViewById(R.id.linearLayout_individualdays).setVisibility(View.VISIBLE);
                   }
                   else if(checkedId == R.id.WeekdaysRG_ID)
                   {
                       view.findViewById(R.id.linearLayout_individualdays).setVisibility(View.INVISIBLE);
                   }
                   else if(checkedId == R.id.WeekendsRG_ID)
                   {
                       view.findViewById(R.id.linearLayout_individualdays).setVisibility(View.INVISIBLE);
                   }

          }
        });


        return view;
    }

    @Override
    public void returnTime(String value) {
        // TODO Auto-generated method stub
        if(flag==false)
        ed1.setText(value);
        else if(flag==true)
        ed2.setText(value);

    }



}

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

日志 ::

12-27 08:55:53.543: E/AndroidRuntime(279): FATAL EXCEPTION: main
12-27 08:55:53.543: E/AndroidRuntime(279): java.lang.ClassCastException: com.project.findmybuffet.BuffetOfferings_MainFragmentActivity
12-27 08:55:53.543: E/AndroidRuntime(279):  at com.project.findmybuffet.TimePickerFragment.onCreateDialog(TimePickerFragment.java:24)
12-27 08:55:53.543: E/AndroidRuntime(279):  at android.support.v4.app.DialogFragment.getLayoutInflater(DialogFragment.java:295)
12-27 08:55:53.543: E/AndroidRuntime(279):  at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:927)
12-27 08:55:53.543: E/AndroidRuntime(279):  at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:1104)
12-27 08:55:53.543: E/AndroidRuntime(279):  at android.support.v4.app.BackStackRecord.run(BackStackRecord.java:682)
12-27 08:55:53.543: E/AndroidRuntime(279):  at android.support.v4.app.FragmentManagerImpl.execPendingActions(FragmentManager.java:1467)
12-27 08:55:53.543: E/AndroidRuntime(279):  at android.support.v4.app.FragmentManagerImpl$1.run(FragmentManager.java:440)
12-27 08:55:53.543: E/AndroidRuntime(279):  at android.os.Handler.handleCallback(Handler.java:587)
12-27 08:55:53.543: E/AndroidRuntime(279):  at android.os.Handler.dispatchMessage(Handler.java:92)
12-27 08:55:53.543: E/AndroidRuntime(279):  at android.os.Looper.loop(Looper.java:123)
12-27 08:55:53.543: E/AndroidRuntime(279):  at android.app.ActivityThread.main(ActivityThread.java:4627)
12-27 08:55:53.543: E/AndroidRuntime(279):  at java.lang.reflect.Method.invokeNative(Native Method)
12-27 08:55:53.543: E/AndroidRuntime(279):  at java.lang.reflect.Method.invoke(Method.java:521)
12-27 08:55:53.543: E/AndroidRuntime(279):  at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:868)
12-27 08:55:53.543: E/AndroidRuntime(279):  at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:626)
12-27 08:55:53.543: E/AndroidRuntime(279):  at dalvik.system.NativeStart.main(Native Method)

{编辑}托管片段活动

BuffetOfferings_MainFragmentActivity.java

public class BuffetOfferings_MainFragmentActivity extends FragmentActivity{

    Button back_button;

    FragmentManager manager;
    FragmentTransaction transaction;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        // TODO Auto-generated method stub
        super.onCreate(savedInstanceState);
        setContentView(R.layout.buffet_offerings_fragment_main_reference);

        Buffet_offerings_breakfast_menu1 breakfast_fragment=new Buffet_offerings_breakfast_menu1();
        Buffet_offerings_lunch_menu1 lunch_fragment=new Buffet_offerings_lunch_menu1();
        Buffet_offerings_dinner_menu1 dinner_fragment=new Buffet_offerings_dinner_menu1();

        manager=getSupportFragmentManager();
        transaction=manager.beginTransaction();

        transaction.add(R.id.BREAKFAST_LAYOUT_ID,breakfast_fragment, "breakfast_menu1_fragment");
        transaction.add(R.id.LUNCH_LAYOUT_ID,lunch_fragment, "lunch_menu1_fragment");
        transaction.add(R.id.DINNER_LAYOUT_ID,dinner_fragment, "dinner_menu1_fragment");

        transaction.commit();



        back_button=(Button) findViewById(R.id.TopNavigationBarRestaurantBuffetOfferingsBackButton);
        back_button.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                // TODO Auto-generated method stub
                finish();

            }
        });









    }

    public void BreakfastRedMenu1(View V){

        Buffet_offerings_breakfast_menu2  breakfast_fragment1=new Buffet_offerings_breakfast_menu2();
        transaction=manager.beginTransaction();
        transaction.replace(R.id.BREAKFAST_LAYOUT_ID, breakfast_fragment1, "Tag1");
        transaction.commit();

    }

    public void LunchRedMenu1(View V){

        Buffet_offerings_lunch_menu2  lunch_fragment1=new Buffet_offerings_lunch_menu2();
        transaction=manager.beginTransaction();
        transaction.replace(R.id.LUNCH_LAYOUT_ID, lunch_fragment1, "Tag2");
        transaction.commit();

    }

    public void DinnerRedMenu1(View V){

        Buffet_offerings_dinner_menu2  dinner_fragment1=new Buffet_offerings_dinner_menu2();
        transaction=manager.beginTransaction();
        transaction.replace(R.id.DINNER_LAYOUT_ID, dinner_fragment1, "Tag3");
        transaction.commit();

    }


    public void BreakfastGreenMenu2(View V){

        Buffet_offerings_breakfast_menu1  breakfast_fragment2=new Buffet_offerings_breakfast_menu1();
        transaction=manager.beginTransaction();
        transaction.replace(R.id.BREAKFAST_LAYOUT_ID, breakfast_fragment2, "Tag4");
        transaction.commit();

    }   

    public void LunchGreenMenu2(View V){

        Buffet_offerings_lunch_menu1  lunch_fragment2=new Buffet_offerings_lunch_menu1();
        transaction=manager.beginTransaction();
        transaction.replace(R.id.LUNCH_LAYOUT_ID, lunch_fragment2, "Tag5");
        transaction.commit();

    }

    public void DinnerGreenMenu2(View V){

        Buffet_offerings_dinner_menu1  dinner_fragment2=new Buffet_offerings_dinner_menu1();
        transaction=manager.beginTransaction();
        transaction.replace(R.id.DINNER_LAYOUT_ID, dinner_fragment2, "Tag6");
        transaction.commit();

    }


}

2 个答案:

答案 0 :(得分:2)

所有片段到片段的通信都是通过关联的Activity完成的。两个碎片永远不应该直接沟通。

http://developer.android.com/training/basics/fragments/communicating.html

您可以作为回调接口参与活动。所以在活动中获取时间然后与片段进行通信。

示例:

为了示例,我正在扩展Activity。您可以扩展FragmentAcitivty和使用支持库并进行适当的导入。

    public class MainActivity extends Activity implements PickTime{

        EditFragment newFragment; 
        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_main);
            newFragment = new EditFragment();
            FragmentManager fragmentManager = getFragmentManager();
            FragmentTransaction transaction = fragmentManager.beginTransaction();
            transaction.replace(R.id.container, newFragment);
            //transaction.addToBackStack(null);
            transaction.commit();
        }

        @Override
        public boolean onCreateOptionsMenu(Menu menu) {
            // Inflate the menu; this adds items to the action bar if it is present.
            getMenuInflater().inflate(R.menu.main, menu);
            return true;
        }

        @Override
        public void returnTime(String value) {
            // TODO Auto-generated method stub
            if(newFragment.isVisible())
            {
                newFragment.setEdittextvalue(value);
            }

        }

    }

仅使用Edittext

进行片段化
public class EditFragment extends Fragment {

    EditText ed;
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
            Bundle savedInstanceState) {
        View v = inflater.inflate(R.layout.fragmentlayout,container,false);

        return v;
    }
    @Override
    public void onActivityCreated(Bundle savedInstanceState) {
        // TODO Auto-generated method stub
        super.onActivityCreated(savedInstanceState);
        ed = (EditText) getView().findViewById(R.id.editText1);
        ed.setOnClickListener(new  OnClickListener()
        {

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

        });
    }
    public void setEdittextvalue(String value) {
        // TODO Auto-generated method stub
        ed.setText(value);

    }
}

TimerPickerFragment

public class TimePickerFragment extends DialogFragment
implements TimePickerDialog.OnTimeSetListener {


    @Override
    public void onAttach(Activity activity) {
        // TODO Auto-generated method stub
        super.onAttach(activity);
        mCallback = (PickTime) activity;
    }

    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

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

答案 1 :(得分:1)

像这样

在Buffet_offerings_breakfast_menu2中初始化mCallback
@Override
public void onAttach(Activity activity) {
    // TODO Auto-generated method stub
    super.onAttach(activity);
    mCallback = (PickTime) activity;
}