Tutorial Android : DatePicker (From & To) Using Dialog With TabHost |
Tsssahhhelahh gegara dengerin lagu Noah yang judulnyaTak lagi sama !!! jadi galo gue :v wkwkkw, patah hati engga tapi galo, gak tau nih galo kenapa wkwkkw, terus gue lampiasin aja buat nulis ke blog ini, dan berhubung gue bukan orang yang begitu normal, jadi curhat gue itu tulisannya dalem bentuk kodingan yee, hahaha jangan heran kalo nanti bentuk tulisannya macem kaya orang mau ngirim email ke alien :v..
Oke gue lanjut aja curhatnya, jadi gue punya kasus nih ceritanya gue pengen bikin DatePicker From and To buat tanggal dari kapan sampe kapan, nahh tapi gw pengen bikin dalem bentuk popup dialog di android, nah gue searching deh tuh tutorialnya dan akhirnya dapet linknya disini, tapi gak sesuai sama keinginan gue karena yang gue pengen tuh dialog yang ada TAB'nya tab 1 itu date_from & tab 2 itu date_to jadi gue modifikasi aja dan bisa dibilang library sih, tapi sayangnya gw blm bisa bikin package library, jadi sementara gw nulis koding aja deh ;)
Step pertama bikin new project dulu di android studio, dan kalo udah buka file MainActivity.java dan bikin perubahan sedikit kaya kode dibawah ini.
package com.bye.project; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.util.Log; import android.view.View; import android.widget.Button; import com.bye.project.helper.DateTimePicker; import com.bye.project.helper.SimpleDateTimePicker; import java.util.Date; /** * Created by Bye Webster on 24/02/17. * Website : http://bye-webster.blogspot.com */ public class MainActivity extends AppCompatActivity implements DateTimePicker.OnDateFromSetListener, DateTimePicker.OnDateToSetListener { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); Button btn_datepicker = (Button)findViewById(R.id.btn_datepicker); btn_datepicker.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { SimpleDateTimePicker simpleDateTimePicker = SimpleDateTimePicker.make( "Plan Your Trip", new Date(), MainActivity.this, MainActivity.this, getSupportFragmentManager() ); // Show It baby ! simpleDateTimePicker.show(); } }); } @Override public void DateFromSet(String date) { Log.d("MainActivity", "Date From : " + date); } @Override public void DateToSet(String date) { Log.d("MainActivity", "Date To : " + date); } }
Lanjut ke step dua, kita membutuhkan file DateTime.java , SimpleDateTimePicker.java dan DateTimePicker.java
Copy paste kode dibawah ini dan beri nama DateTime.java yaaa ;)
package com.bye.project.helper; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.Calendar; import java.util.Date; /** * Created by Bye Webster on 24/02/17. * Website : http://bye-webster.blogspot.com */ public class DateTime { public static final String DATE_FORMAT = "yyyy-MM-dd HH:mm:ss"; private Date mDate; private Calendar mCalendar; /** * Constructor with no parameters which will create DateTime * Object with the current date and time */ public DateTime() { this(new Date()); } /** * Constructor with Date parameter which will initialize the * object to the date specified * @param date */ public DateTime(Date date) { mDate = date; mCalendar = Calendar.getInstance(); mCalendar.setTime(mDate); } /** * Constructor with DateFormat and DateString which will be * used to initialize the object to the date string specified * @param dateFormat String DateFormat * @param dateString Date in String */ public DateTime(String dateFormat, String dateString) { mCalendar = Calendar.getInstance(); SimpleDateFormat mFormat = new SimpleDateFormat(dateFormat); try { mDate = mFormat.parse(dateString); mCalendar.setTime(mDate); } catch (ParseException e) { e.printStackTrace(); } } /** * Constructor with DateString formatted as default DateFormat * defined in DATE_FORMAT variable * @param dateString */ public DateTime(String dateString) { this(DATE_FORMAT, dateString); } /** * Constructor with Year, Month, Day, Hour, Minute, and Second * which will be use to set the date to * @param year Year * @param monthOfYear Month of Year * @param dayOfMonth Day of Month * @param hourOfDay Hour of Day * @param minuteOfHour Minute * @param secondOfMinute Second */ public DateTime(int year, int monthOfYear, int dayOfMonth, int hourOfDay, int minuteOfHour, int secondOfMinute) { mCalendar = Calendar.getInstance(); mCalendar.set(year, monthOfYear, dayOfMonth, hourOfDay, minuteOfHour, secondOfMinute); mDate = mCalendar.getTime(); } /** * Constructor with Year, Month Day, Hour, Minute which * will be use to set the date to * @param year Year * @param monthOfYear Month of Year * @param dayOfMonth Day of Month * @param hourOfDay Hour of Day * @param minuteOfHour Minute */ public DateTime(int year, int monthOfYear, int dayOfMonth, int hourOfDay, int minuteOfHour) { this(year, monthOfYear, dayOfMonth, hourOfDay, minuteOfHour, 0); } /** * Constructor with Date only (no time) * @param year Year * @param monthOfYear Month of Year * @param dayOfMonth Day of Month */ public DateTime(int year, int monthOfYear, int dayOfMonth) { this(year, monthOfYear, dayOfMonth, 0,0,0); } public Date getDate() { return mDate; } public Calendar getCalendar() { return mCalendar; } public String getDateString(String dateFormat) { SimpleDateFormat mFormat = new SimpleDateFormat(dateFormat); return mFormat.format(mDate); } public String getDateString() { return getDateString(DATE_FORMAT); } public int getYear() { return mCalendar.get(Calendar.YEAR); } public int getMonthOfYear() { return mCalendar.get(Calendar.MONTH); } public int getDayOfMonth() { return mCalendar.get(Calendar.DAY_OF_MONTH); } public int getHourOfDay() { return mCalendar.get(Calendar.HOUR_OF_DAY); } public int getMinuteOfHour() { return mCalendar.get(Calendar.MINUTE); } public int getSecondOfMinute() { return mCalendar.get(Calendar.SECOND); } }
Kalo udah di copy paste, lanjut bikin file bernama SampleDateTimePicker.java dan isi file'nya dengan kode dibawah ini :
package com.bye.project.helper; import android.support.v4.app.Fragment; import android.support.v4.app.FragmentManager; import android.support.v4.app.FragmentTransaction; import java.util.Date; /** * Created by Bye Webster on 24/02/17. * Website : http://bye-webster.blogspot.com */ public class SimpleDateTimePicker { private CharSequence mDialogTitle; private Date mInitDate; private DateTimePicker.OnDateFromSetListener mOnDateFromSetListener; private DateTimePicker.OnDateToSetListener mOnDateToSetListener; private FragmentManager mFragmentManager; /** * Private constructor that can only be access using the make method * @param dialogTitle Title of the Date Time Picker Dialog * @param initDate Date object to use to set the initial Date and Time * @param onDateFromSetListener OnDateTimeSetListener interface * @param onDateToSetListener onDateToSetListener interface * @param fragmentManager Fragment Manager from the activity */ private SimpleDateTimePicker(CharSequence dialogTitle, Date initDate, DateTimePicker.OnDateFromSetListener onDateFromSetListener, DateTimePicker.OnDateToSetListener onDateToSetListener, FragmentManager fragmentManager) { // Find if there are any DialogFragments from the FragmentManager FragmentTransaction mFragmentTransaction = fragmentManager.beginTransaction(); Fragment mDateTimeDialogFrag = fragmentManager.findFragmentByTag( DateTimePicker.TAG_FRAG_DATE_TIME ); // Remove it if found if(mDateTimeDialogFrag != null) { mFragmentTransaction.remove(mDateTimeDialogFrag); } mFragmentTransaction.addToBackStack(null); mDialogTitle = dialogTitle; mInitDate = initDate; mOnDateFromSetListener = onDateFromSetListener; mOnDateToSetListener = onDateToSetListener; mFragmentManager = fragmentManager; } /** * Creates a new instance of the SimpleDateTimePicker * @param dialogTitle Title of the Date Time Picker Dialog * @param initDate Date object to use to set the initial Date and Time * @param onDateFromSetListener OnDateFromSetListener interface * @param onDateToSetListener OnDateToSetListener interface * @param fragmentManager Fragment Manager from the activity * @return Returns a SimpleDateTimePicker object */ public static SimpleDateTimePicker make(CharSequence dialogTitle, Date initDate, DateTimePicker.OnDateFromSetListener onDateFromSetListener, DateTimePicker.OnDateToSetListener onDateToSetListener, FragmentManager fragmentManager) { return new SimpleDateTimePicker(dialogTitle, initDate, onDateFromSetListener,onDateToSetListener, fragmentManager); } /** * Shows the DateTimePicker Dialog */ public void show() { // Create new DateTimePicker DateTimePicker mDateTimePicker = DateTimePicker.newInstance(mDialogTitle,mInitDate); mDateTimePicker.setOnDateFromSetListener(mOnDateFromSetListener); mDateTimePicker.setOnDateToSetListener(mOnDateToSetListener); mDateTimePicker.show(mFragmentManager, DateTimePicker.TAG_FRAG_DATE_TIME); } }
Nah udah di copy paste kan..?? yang terakhir nih, ini file yang library'nya nih nama filenya DateTimePicker.java dan ente copy paste aja langsung gak pake lama ;)
package com.bye.project.helper; import android.app.Activity; import android.app.AlertDialog; import android.app.Dialog; import android.content.Context; import android.content.DialogInterface; import android.os.Bundle; import android.support.v4.app.DialogFragment; import android.view.LayoutInflater; import android.view.View; import android.widget.DatePicker; import android.widget.TabHost; import com.bye.project.R; import java.util.Date; /** * Created by Bye Webster on 24/02/17. * Website : http://bye-webster.blogspot.com */ public class DateTimePicker extends DialogFragment { public static final String TAG_FRAG_DATE_TIME = "fragDateTime"; private static final String KEY_DIALOG_TITLE = "dialogTitle"; private static final String KEY_INIT_DATE = "initDate"; private static final String TAG_DATE = "date"; private static final String TAG_TIME = "time"; private Context mContext; private ButtonClickListener mButtonClickListener; private OnDateFromSetListener mOnDateFromSetListener; private OnDateToSetListener mOnDateToSetListener; private Bundle mArgument; private DatePicker mDatePickerFrom; private DatePicker mDatePickerTo; // DialogFragment constructor must be empty public DateTimePicker() { } @Override public void onAttach(Activity activity) { super.onAttach(activity); mContext = activity; mButtonClickListener = new ButtonClickListener(); } /** * * @param dialogTitle Title of the DateTimePicker DialogFragment * @param initDate Initial Date and Time set to the Date and Time Picker * @return Instance of the DateTimePicker DialogFragment */ public static DateTimePicker newInstance(CharSequence dialogTitle, Date initDate) { // Create a new instance of DateTimePicker DateTimePicker mDateTimePicker = new DateTimePicker(); // Setup the constructor parameters as arguments Bundle mBundle = new Bundle(); mBundle.putCharSequence(KEY_DIALOG_TITLE, dialogTitle); mBundle.putSerializable(KEY_INIT_DATE, initDate); mDateTimePicker.setArguments(mBundle); // Return instance with arguments return mDateTimePicker; } @Override public Dialog onCreateDialog(Bundle savedInstanceState) { // Retrieve Argument passed to the constructor mArgument = getArguments(); // Use an AlertDialog Builder to initially create the Dialog AlertDialog.Builder mBuilder = new AlertDialog.Builder(mContext); // Setup the Dialog mBuilder.setTitle(mArgument.getCharSequence(KEY_DIALOG_TITLE)); mBuilder.setNegativeButton(android.R.string.no,mButtonClickListener); mBuilder.setPositiveButton(android.R.string.yes,mButtonClickListener); // Create the Alert Dialog AlertDialog mDialog = mBuilder.create(); // Set the View to the Dialog mDialog.setView( createDateTimeView(mDialog.getLayoutInflater()) ); // Return the Dialog created return mDialog; } /** * Inflates the XML Layout and setups the tabs * @param layoutInflater Layout inflater from the Dialog * @return Returns a view that will be set to the Dialog */ private View createDateTimeView(LayoutInflater layoutInflater) { // Inflate the XML Layout using the inflater from the created Dialog View mView = layoutInflater.inflate(R.layout.date_time_picker,null); // Extract the TabHost TabHost mTabHost = (TabHost) mView.findViewById(R.id.tab_host); mTabHost.setup(); // Create Date From Tab and add to TabHost TabHost.TabSpec mDateFromTab = mTabHost.newTabSpec(TAG_DATE); mDateFromTab.setIndicator("Date From"); mDateFromTab.setContent(R.id.date_from_content); mTabHost.addTab(mDateFromTab); // Create Date To Tab and add to TabHost TabHost.TabSpec mDateToTab = mTabHost.newTabSpec(TAG_DATE); mDateToTab.setIndicator("Date To"); mDateToTab.setContent(R.id.date_to_content); mTabHost.addTab(mDateToTab); // Retrieve Date from Arguments sent to the Dialog DateTime mDateTime = new DateTime((Date) mArgument.getSerializable(KEY_INIT_DATE)); // Initialize Date and Time Pickers mDatePickerFrom = (DatePicker) mView.findViewById(R.id.date_picker_from); mDatePickerFrom.setBackgroundColor(getResources().getColor(R.color.colorPrimary)); mDatePickerTo = (DatePicker) mView.findViewById(R.id.date_picker_to); mDatePickerTo.setBackgroundColor(getResources().getColor(R.color.colorPrimary)); // Return created view return mView; } /** * Sets the OnDateFromSetListener interface * @param onDateFromSetListener Interface that is used to send the Date and Time * to the calling object */ public void setOnDateFromSetListener(OnDateFromSetListener onDateFromSetListener) { mOnDateFromSetListener = onDateFromSetListener; } /** * Sets the OnDateToSetListener interface * @param onDateToSetListener Interface that is used to send the Date and Time * to the calling object */ public void setOnDateToSetListener(OnDateToSetListener onDateToSetListener) { mOnDateToSetListener = onDateToSetListener; } private class ButtonClickListener implements DialogInterface.OnClickListener { @Override public void onClick(DialogInterface dialogInterface, int result) { // Determine if the user selected Ok if(DialogInterface.BUTTON_POSITIVE == result) { /* Example to get day,month and year int day = datePicker.getDayOfMonth(); int month = datePicker.getMonth() + 1; int year = datePicker.getYear(); */ String from = String.valueOf(mDatePickerFrom.getYear()+"-"+(mDatePickerFrom.getMonth() + 1)+"-"+mDatePickerFrom.getDayOfMonth()); String to = String.valueOf(mDatePickerTo.getYear()+"-"+(mDatePickerTo.getMonth() + 1)+"-"+mDatePickerTo.getDayOfMonth()); System.out.println("FROM DATE : " + from); System.out.println("TO DATE : " + to); if(from!=null) mOnDateFromSetListener.DateFromSet(from); if(to!=null) mOnDateToSetListener.DateToSet(to); } } } /** * Interface for sending the Date From to the calling object */ public interface OnDateFromSetListener { public void DateFromSet(String dateFrom); } /** * Interface for sending the Date To to the calling object */ public interface OnDateToSetListener { public void DateToSet(String dateTo); } }
Dan yang terakhir nih, file bernama DateTimePicker.java membutuhkan file date_time_picker.xml dan coba langsung copy paste aja biar cepet kelar sharing kita kali ini ;)
<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:id="@+id/date_time" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical"> <!-- TabHost that will hold the Tabs and its content --> <TabHost android:id="@+id/tab_host" android:layout_width="match_parent" android:layout_height="match_parent"> <LinearLayout android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical"> <!-- TabWidget that will hold the Tabs --> <TabWidget android:id="@android:id/tabs" android:layout_width="match_parent" android:layout_height="match_parent" /> <!-- Layout that will hold the content of the Tabs --> <FrameLayout android:id="@android:id/tabcontent" android:layout_width="match_parent" android:layout_height="match_parent"> <!-- Layout for the DatePicker --> <LinearLayout android:id="@+id/date_from_content" android:orientation="vertical" android:layout_width="match_parent" android:layout_height="match_parent"> <DatePicker android:id="@+id/date_picker_from" android:layout_width="match_parent" android:layout_height="match_parent" android:calendarViewShown="false" /> </LinearLayout> <!-- Layout for the TimePicker --> <LinearLayout android:id="@+id/date_to_content" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical"> <DatePicker android:id="@+id/date_picker_to" android:layout_width="match_parent" android:layout_height="match_parent" android:calendarViewShown="false" /> </LinearLayout> </FrameLayout> </LinearLayout> </TabHost> </LinearLayout>Ini hasil dari kodingan diatas kalo di run ;)
Example Project DatePicker ! |
Okeehhh sekian dulu dan terima kasihh, silahkan di implementasikan dan semoga jalan, klo gak jalan download project di link yang ada diatas tulisan ini :D , dan kalo ada yang pengen ditanyain tanya aja langsung & jangan sungkan okey ;)
No comments:
Post a Comment