Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
430 views
in Technique[技术] by (71.8m points)

java - Simple timepicker for a fragment activity

I am trying to launch a timepicker from a edittext in a fragment

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

Log::

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)

{Edit} hosted fragment activity

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

    }


}
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

All Fragment-to-Fragment communication is done through the associated Activity. Two Fragments should never communicate directly.

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

You can interface as a call back to the activity. So get the time in activity and then communicate to fragment.

Example:

For the example sake i am extending Activity. You can extend FragmentAcitivty ans use support library and make proper imports.

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

        }

    }

Fragment with just a 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());
        }
    }
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...