is it possible to make a date picker in android app as in an iPhone app.
i saw a date picker in i phone app having a Done and cancel buttons. the month , year and date are been chosen by scrolling it, how can i make such a one in my android app
DatePicker and Date Picker tutorial.
Your XML Layout
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="vertical">
<TextView android:id="#+id/dateDisplay"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text=""/>
<Button android:id="#+id/pickDate"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Date Picker"/>
</LinearLayout>
Your Activity Class
public class pickerdate extends Activity {
/** Called when the activity is first created. */
private TextView mDateDisplay;
private Button mPickDate;
private int mYear;
private int mMonth;
private int mDay;
static final int DATE_DIALOG_ID = 0;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
mDateDisplay = (TextView) findViewById(R.id.dateDisplay);
mPickDate = (Button) findViewById(R.id.pickDate);
mPickDate.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
showDialog(DATE_DIALOG_ID);
}
});
final Calendar c = Calendar.getInstance();
mYear = c.get(Calendar.YEAR);
mMonth = c.get(Calendar.MONTH);
mDay = c.get(Calendar.DAY_OF_MONTH);
updateDisplay();
}
private void updateDisplay() {
mDateDisplay.setText(
new StringBuilder()
// Month is 0 based so add 1
.append(mMonth + 1).append("-")
.append(mDay).append("-")
.append(mYear).append(" "));
}
private DatePickerDialog.OnDateSetListener mDateSetListener =
new DatePickerDialog.OnDateSetListener() {
public void onDateSet(DatePicker view, int year,
int monthOfYear, int dayOfMonth) {
mYear = year;
mMonth = monthOfYear;
mDay = dayOfMonth;
updateDisplay();
}
};
#Override
protected Dialog onCreateDialog(int id) {
switch (id) {
case DATE_DIALOG_ID:
return new DatePickerDialog(this,
mDateSetListener,
mYear, mMonth, mDay);
}
return null;
}
}
Related
This is my first time asking a question.
I have created a scrolling calendar using ViewPager2 and have completed the overall framework, but I am facing one major problem.
That is, when I start the screen, I click once on the cell in question, scroll to the next or previous month, click on the calendar cell again, and scroll back to the original screen again, but the background color of the cell I clicked on first does not disappear.
Can you help me resolve this issue?
Here is my current code.
MonthDateManagerAdapter.java
public class MonthDateManagerAdapter {
public static final int DAYS_OF_WEEK = 7;
public static final int WEEKS_OF_CALENDAR = 6;
Calendar Cal = Calendar.getInstance();
Calendar LastMonthCalendar = Calendar.getInstance();
Calendar NextMonthCalendar = Calendar.getInstance();
public MonthDateManagerAdapter(Date date) {
Cal.setTime(date);
}
public int getDayCount(){
return DAYS_OF_WEEK* WEEKS_OF_CALENDAR;
}
public List<Date> getDays(){
Date StartDate = Cal.getTime();
Cal.set(Calendar.DATE,1);
int DayOfWeek = Cal.get(Calendar.DAY_OF_WEEK)-1;
Cal.add(Calendar.DATE,-DayOfWeek);
ArrayList<Date> list = new ArrayList<>();
for(int Calendar_list = 0; Calendar_list < getDayCount(); ++Calendar_list){
list.add(Cal.getTime());
Cal.add(Calendar.DATE,1);
}
Cal.setTime(StartDate);
return list;
}
private boolean IsToday(Date TodayDate){
SimpleDateFormat sdf = new SimpleDateFormat("yyyy.MM.dd", Locale.JAPAN);
String Today = sdf.format(Calendar.getInstance().getTime());
return Today.equals(sdf.format(TodayDate));
}
private boolean isCurrentMonth(Date MonthDate){
SimpleDateFormat sdf = new SimpleDateFormat("yyyy.MM", Locale.JAPAN);
String FormatMonthChange = sdf.format(Cal.getTime());
return FormatMonthChange.equals(sdf.format(MonthDate));
}
#SuppressLint("SimpleDateFormat")
private boolean isSelectDate(Date SelectDate, #NonNull Context context){
SharedPreferences YearMonthDayPref = context.getSharedPreferences("HeadYearMonthDay", Context.MODE_PRIVATE);
String Year = YearMonthDayPref.getString("HeadYear","0");
String Month = YearMonthDayPref.getString("HeadMonth","0");
String Day = YearMonthDayPref.getString("HeadDay","0");
String YearMonthDay = Year + "-" + Month + "-" + Day;
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
Date date = null;
try{
date = sdf.parse(YearMonthDay);
}catch (ParseException e){
e.printStackTrace();
}
assert date != null;
return date.equals(SelectDate);
}
private int getDaysOfWeek(Date date){
Calendar Cal = Calendar.getInstance();
Cal.setTime(date);
return Cal.get(Calendar.DAY_OF_WEEK);
}
public static class MonthCalendarAdapter extends RecyclerView.Adapter<MonthCalendarAdapter.MyMonthCalendarViewHolder> {
final LayoutInflater CalendarCellInflater;
private final MonthDateManagerAdapter manager;
private final List<Date> dateList;
private final CalendarMonthOnItemClick CalendarOnItem;
private final Context context;
public MonthCalendarAdapter(Context context, Date date, CalendarMonthOnItemClick calendarOnItem) {
CalendarCellInflater = LayoutInflater.from(context);
this.CalendarOnItem = calendarOnItem;
manager = new MonthDateManagerAdapter(date);
dateList = manager.getDays();
this.context = context;
}
#NonNull
#Override
public MyMonthCalendarViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
LayoutInflater inflater = LayoutInflater.from(parent.getContext());
View view = inflater.inflate(R.layout.calendar_cell, parent, false);
RecyclerView.LayoutParams params = new RecyclerView.LayoutParams
(parent.getWidth() / DAYS_OF_WEEK, parent.getHeight() / WEEKS_OF_CALENDAR);
view.setLayoutParams(params);
return new MyMonthCalendarViewHolder(view, CalendarOnItem);
}
#SuppressLint("NotifyDataSetChanged")
#Override
public void onBindViewHolder(#NonNull MyMonthCalendarViewHolder holder, int position) {
Date date = dateList.get(position);
SimpleDateFormat sdf = new SimpleDateFormat("d", Locale.JAPAN);
holder.CalendarDate.setText(sdf.format(date));
if (manager.IsToday(date)) {
holder.itemView.setBackgroundColor(context.getColor(R.color.CalendarOnClickCell));
}
int ColorId = manager.getDaysOfWeek(date);
switch (ColorId) {
case 1:
ColorId = Color.RED;
break;
case 7:
ColorId = Color.BLUE;
break;
default:
ColorId = Color.BLACK;
}
holder.CalendarDate.setTextColor(ColorId);
if (!manager.isCurrentMonth(date)) {
holder.CalendarDate.setTextColor(Color.LTGRAY);
}
SharedPreferences YearMonthDayPref = context.getSharedPreferences("HeadYearMonthDay", Context.MODE_PRIVATE);
boolean getFlag = YearMonthDayPref.getBoolean("HeadFlag", false);
int HeadPosition = YearMonthDayPref.getInt("HeadPosition", 0);
if(getFlag) {
if (manager.isSelectDate(date, context) && manager.IsToday(date)) {
GradientDrawable drawable = new GradientDrawable();
drawable.mutate();
drawable.setShape(GradientDrawable.RECTANGLE);
drawable.setColor(context.getColor(R.color.CalendarOnClickCell));
drawable.setStroke(dpFromPx(context), Color.rgb(0, 0, 0));
holder.CalendarRootBackground.setBackground(drawable);
} else if (HeadPosition == position) {
GradientDrawable drawable = new GradientDrawable();
drawable.mutate();
drawable.setShape(GradientDrawable.RECTANGLE);
drawable.setStroke(dpFromPx(context), Color.rgb(0, 0, 0));
holder.CalendarRootBackground.setBackground(drawable);
}
}
holder.itemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String CalendarFormatChange = String.valueOf(holder.CalendarDate.getText());
CalendarOnItem.calendarOnItem(holder.getAdapterPosition(), CalendarFormatChange);
}
});
}
#Override
public int getItemCount() {
return manager.getDayCount();
}
//ViewHolder
public static class MyMonthCalendarViewHolder extends RecyclerView.ViewHolder {
public final TextView CalendarDate;
private final ConstraintLayout CalendarRootBackground;
final CalendarMonthOnItemClick calendarOnItem;
public MyMonthCalendarViewHolder(#NonNull View view,CalendarMonthOnItemClick calendarOnItem) {
super(view);
//↓customcell
CalendarDate = view.findViewById(R.id.CalendarCellText);
CalendarRootBackground = view.findViewById(R.id.CalendarRootParent);
this.calendarOnItem = calendarOnItem;
}
}
}
private static int dpFromPx(#NonNull Context context){
DisplayMetrics displayMetrics = context.getResources().getDisplayMetrics();
return Math.round(3 * (displayMetrics.xdpi/ DisplayMetrics.DENSITY_DEFAULT));
}
MainActivity.java
public class MainActivity extends AppCompatActivity {
private TextView MonYearText;
#Override
protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
ChangeStatusColor();
setContentView(R.layout.activity_main);
ViewPager2 viewPager2 = findViewById(R.id.RootViewPager);
MonYearText = findViewById(R.id.MonYearText);
CalendarFragmentStateAdapter adapter = new CalendarFragmentStateAdapter(this);
viewPager2.setAdapter(adapter);
viewPager2.registerOnPageChangeCallback(new CalendarRegisterOnPageChangeCallback());
viewPager2.setOrientation(ViewPager2.ORIENTATION_HORIZONTAL);
viewPager2.setCurrentItem(CalendarManger.TODAY_COUNT,false);
}
private class CalendarRegisterOnPageChangeCallback extends ViewPager2.OnPageChangeCallback{
#Override
public void onPageSelected(int position) {
super.onPageSelected(position);
MonYearText.setText(CalendarManger.positionToDateString(position));
String SharedPreferText = String.valueOf(MonYearText.getText());
setYearTextSharedPreferences(SharedPreferText);
}
#Override
public void onPageScrollStateChanged(int state) {
if(state == 1){
setYearMonthFlagChange();
}
super.onPageScrollStateChanged(state);
}
}
public static class CalendarManger{
public static final int MAX_COUNT = Integer.MAX_VALUE;
public static final int TODAY_COUNT = MAX_COUNT/2;
public static final String DATE_PATTERN = "yyyy年MM月";
static Calendar Cal = Calendar.getInstance();
#NonNull
public static String positionToDateString(int position){
Date date = Cal.getTime();
Cal.add(Calendar.MONTH,position- TODAY_COUNT);
#SuppressLint("SimpleDateFormat") SimpleDateFormat sdf = new SimpleDateFormat(DATE_PATTERN);
String DateString = sdf.format(Cal.getTime());
Cal.setTime(date);
return DateString;
}
}
private void ChangeStatusColor(){
getWindow().clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
getWindow().addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS);
getWindow().setStatusBarColor(getResources().getColor(R.color.white,getTheme()));
}
#SuppressLint("CommitPrefEdits")
private void setYearTextSharedPreferences(#NonNull String YearMonth){
String Year = YearMonth.substring(0,4);
String Month = YearMonth.substring(5,7);
SharedPreferences YearMonthPref = getSharedPreferences("HeadYearMonthDay", Context.MODE_PRIVATE);
SharedPreferences.Editor YearMonthEdit = YearMonthPref.edit();
YearMonthEdit.putString("HeadYear",Year);
YearMonthEdit.putString("HeadMonth",Month);
YearMonthEdit.apply();
}
#SuppressLint("CommitPrefEdits")
private void setYearMonthFlagChange(){
SharedPreferences YearMonthPref = getSharedPreferences("HeadYearMonthDay", Context.MODE_PRIVATE);
SharedPreferences.Editor YearMonthEdit = YearMonthPref.edit();
YearMonthEdit.putBoolean("HeadFlag",false);
YearMonthEdit.apply();
FragmentManager manager = getSupportFragmentManager();
manager.beginTransaction()
.add(new CalendarMonthFragment(),"Fragment")
.commit();
}
}
CalendarMonthFragment.java
public class CalendarMonthFragment extends Fragment implements CalendarMonthOnItemClick{
private Date date = new Date();
private RecyclerView calendarRecyclerView;
private static final String CALENDAR_KEY = "CALENDAR_KEY";
#Override
public void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
ChangeStatusColor();
Bundle bundle = getArguments();
SimpleDateFormat sdf = new SimpleDateFormat(MainActivity.CalendarManger.DATE_PATTERN,Locale.JAPAN);
if (bundle != null) {
String DateText = bundle.getString(CALENDAR_KEY,"0");
if(!DateText.equals("0")){
try {
date = sdf.parse(DateText);
} catch (ParseException e) {
e.printStackTrace();
}
}
}
}
#Nullable
#Override
public View onCreateView(#NonNull LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_calendar_month,container,false);
calendarRecyclerView = view.findViewById(R.id.CalendarRecycle);
setMonthView();
return view;
}
#SuppressLint("NotifyDataSetChanged")
public void setMonthView(){
Activity activity = getActivity();
assert activity != null;
MonthDateManagerAdapter.MonthCalendarAdapter adapter = new MonthDateManagerAdapter.MonthCalendarAdapter(requireContext(),date,this);
calendarRecyclerView.setAdapter(adapter);
RecyclerView.LayoutManager manager = new GridLayoutManager(requireContext(),MonthDateManagerAdapter.DAYS_OF_WEEK,LinearLayoutManager.VERTICAL,false);
calendarRecyclerView.setLayoutManager(manager);
calendarRecyclerView.suppressLayout(false);
Objects.requireNonNull(calendarRecyclerView.getAdapter()).notifyDataSetChanged();
calendarRecyclerView.suppressLayout(true);
}
#NonNull
public static CalendarMonthFragment newInstance(String Key_Value) {
Bundle args = new Bundle();
args.putString(CALENDAR_KEY,Key_Value);
CalendarMonthFragment fragment = new CalendarMonthFragment();
fragment.setArguments(args);
return fragment;
}
private void ChangeStatusColor(){
Activity activity = getActivity();
if(activity != null){
activity.getWindow().clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
activity.getWindow().addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS);
activity.getWindow().setStatusBarColor(getResources().getColor(R.color.white,activity.getTheme()));
}
}
#Override
#SuppressLint({"CommitPrefEdits", "NotifyDataSetChanged"})
public void calendarOnItem(int Position, String Day) {
Activity activity = getActivity();
assert activity != null;
SharedPreferences HeadDayPref = activity.getSharedPreferences("HeadYearMonthDay", Context.MODE_PRIVATE);
SharedPreferences.Editor HeadDayEdit = HeadDayPref.edit();
HeadDayEdit.putString("HeadDay",Day);
HeadDayEdit.putBoolean("HeadFlag",true);
HeadDayEdit.putInt("HeadPosition",Position);
HeadDayEdit.apply();
setMonthView();
}
}
custom_cell.Xml
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout
android:id="#+id/CalendarRootParent"
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:id="#+id/CalendarCellText"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/CalendarCellText"
android:textColor="#color/black"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.06"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintVertical_bias="0.05" />
<View
android:id="#+id/TopView"
android:layout_width="wrap_content"
android:layout_height="1dp"
android:background="#color/defaultBarLine"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
<View
android:id="#+id/BottomView"
android:layout_width="wrap_content"
android:layout_height="1dp"
android:background="#color/defaultBarLine"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent" />
<View
android:id="#+id/LeftView"
android:layout_width="1dp"
android:layout_height="wrap_content"
android:background="#color/defaultBarLine"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
<View
android:id="#+id/RightView"
android:layout_width="1dp"
android:layout_height="wrap_content"
android:background="#color/defaultBarLine"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
</androidx.constraintlayout.widget.ConstraintLayout>
calendar_select_frame.xml
<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
android:shape="rectangle">
<stroke
android:width="3dp"
android:color="#color/black"/>
</shape>
To resolve this issue.
I tried to solve it myself by calling notifydatasetchanged() in the adapter of RecycleView and notifydatasetchanged() in the adapter of ViewPager2, but I cannot reach a solution.
trying to solve my timer error in android stuido.
i have 2 xml text views where one is start time and one is finsih time
a user must choose there start and finish time to fill in the details
i have most the code correct just cant figure out this one line
also would like if possible i know its already working but for my date picker how do i make say "Friday 3/04/2020"
here is my main java class
public class ChoseSession extends AppCompatActivity implements AdapterView.OnItemSelectedListener
{
private static final String TAG = "ChooseSession";
private TextView displayDate;
private DatePickerDialog.OnDateSetListener mDateSetListener;
private TextView displayStartTime;
private TextView displayFinishTime;
private TimePickerDialog.OnTimeSetListener mSTimeSetListener;
private TimePickerDialog.OnTimeSetListener mFTimeSetListener;
//------------------------------------------------------------------------------------------------
public Button confirmbookingBTN;
public void returnMain()
{
confirmbookingBTN = (Button)findViewById(R.id.confirmBooking);
confirmbookingBTN.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View v)
{
Intent book = new Intent(ChoseSession.this, Results.class);
startActivity(book);
}
});
}
//-----------------------------------------------------------------------------------------------
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_chose_session);
//-----------------------------------------------------------------------------------------------
returnMain();
//-----------------------------------------------------------------------------------------------
displayStartTime = findViewById(R.id.startTimeView);
displayFinishTime = findViewById(R.id.finishTimeView);
displayStartTime.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View v)
{
Calendar cal = Calendar.getInstance();
int hour = cal.get(Calendar.HOUR);
int minute = cal.get(Calendar.MINUTE);
TimePickerDialog timedialog = new TimePickerDialog(this, hour, minute, DateFormat.is24HourFormat(getContext())););
timedialog.getWindow().setBackgroundDrawable((new ColorDrawable((Color.TRANSPARENT))));
timedialog.show();
}
});
displayFinishTime.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View v)
{
Calendar cal = Calendar.getInstance();
int hour = cal.get(Calendar.HOUR);
int minute = cal.get(Calendar.MINUTE);
TimePickerDialog timedialog = new TimePickerDialog(this, hour, minute, DateFormat.is24HourFormat(getContext())););
timedialog.getWindow().setBackgroundDrawable((new ColorDrawable((Color.TRANSPARENT))));
timedialog.show();
}
});
mSTimeSetListener = new TimePickerDialog.OnTimeSetListener()
{
#Override
public void onTimeSet(TimePicker view, int hourOfDay, int minute)
{
displayStartTime.setText((hourOfDay+":"+minute));
}
};
mFTimeSetListener = new TimePickerDialog.OnTimeSetListener()
{
#Override
public void onTimeSet(TimePicker view, int hourOfDay, int minute)
{
displayFinishTime.setText((hourOfDay+":"+minute));
}
};
//-----------------------------------------------------------------------------------------------
displayDate = (TextView) findViewById(R.id.dateView);
displayDate.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View v)
{
Calendar cal = Calendar.getInstance();
int year = cal.get(Calendar.YEAR);
int month = cal.get(Calendar.MONTH);
int day = cal.get(Calendar.DAY_OF_MONTH);
DatePickerDialog dialog = new DatePickerDialog(ChoseSession.this, android.R.style.Theme_Holo_Light_Dialog_MinWidth, mDateSetListener, year, month, day);
dialog.getWindow().setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));
dialog.show();
}
});
mDateSetListener = new DatePickerDialog.OnDateSetListener()
{
#Override
public void onDateSet(DatePicker view, int y, int m, int d)
{
m = m + 1;
Log.d(TAG, "onDataSet: date: " + y + "/" + m + "/" + d);
String date = d+"/"+m+"/"+"/"+y;
displayDate.setText(date);
}
};
//-----------------------------------------------------------------------------------------------
Spinner sSpinner = findViewById(R.id.spinnerSessionChoosing);
ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(this, R.array.sessionNames, android.R.layout.simple_spinner_item);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
sSpinner.setAdapter(adapter);
sSpinner.setOnItemSelectedListener(this);
//-----------------------------------------------------------------------------------------------
}
private Context getContext()
{
}
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
String textSession = parent.getItemAtPosition(position).toString();
//Toast.makeText(parent.getContext(), textSession, Toast.LENGTH_SHORT).show();
}
#Override
public void onNothingSelected(AdapterView<?> parent)
{
}
//-----------------------------------------------------------------------------------------------
}
my XML
<TextView
android:id="#+id/finishTimeView"
android:layout_width="161dp"
android:layout_height="25dp"
android:layout_marginEnd="44dp"
android:layout_marginBottom="99dp"
android:text="Choose Finish Time"
android:textAlignment="center"
android:textColor="#000000"
android:textSize="18sp"
app:layout_constraintBottom_toTopOf="#+id/confirmBooking"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toEndOf="#+id/timefinishText"
app:layout_constraintTop_toBottomOf="#+id/startTimeView" />
<TextView
android:id="#+id/startTimeView"
android:layout_width="161dp"
android:layout_height="25dp"
android:layout_marginEnd="44dp"
android:layout_marginBottom="40dp"
android:text="Choose Start Time"
android:textAlignment="center"
android:textColor="#000000"
android:textSize="18sp"
app:layout_constraintBottom_toTopOf="#+id/finishTimeView"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toEndOf="#+id/timestartText"
app:layout_constraintTop_toBottomOf="#+id/dateView" />
the answer to the java time dialog
displayStartTime = findViewById(R.id.startTimeView);
displayFinishTime = findViewById(R.id.finishTimeView);
displayStartTime.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View v)
{
Calendar cal = Calendar.getInstance();
final int hour = cal.get(Calendar.HOUR_OF_DAY);
final int min = cal.get(Calendar.MINUTE);
TimePickerDialog sTimePickerDialog = new TimePickerDialog(tContext, new TimePickerDialog.OnTimeSetListener()
{
#Override
public void onTimeSet(TimePicker view, int hourOfDay, int minute)
{
displayStartTime.setText(hourOfDay+":"+minute);
}
},hour, min, android.text.format.DateFormat.is24HourFormat(tContext));
sTimePickerDialog.show();
}
});
displayFinishTime.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View v)
{
Calendar cal = Calendar.getInstance();
final int hour = cal.get(Calendar.HOUR_OF_DAY);
final int min = cal.get(Calendar.MINUTE);
TimePickerDialog fTimePickerDialog = new TimePickerDialog(tContext, new TimePickerDialog.OnTimeSetListener()
{
#Override
public void onTimeSet(TimePicker view, int hourOfDay, int minute)
{
displayFinishTime.setText(hourOfDay+":"+minute);
}
},hour, min, android.text.format.DateFormat.is24HourFormat(tContext));
fTimePickerDialog.show();
}
});
I'm creating an app with two DatePicker to set a start and an end dates. As the DatePicker are called from DialogFragments, I set two tags to differentiate the results in the main activity:
#Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.sel_start_date:
DialogFragment startDatePicker = new DatePickerFragment();
startDatePicker.show(getSupportFragmentManager(), START_DATE_PICKER_TAG);
break;
case R.id.sel_end_date:
DialogFragment endDatePicker = new DatePickerFragment();
endDatePicker.show(getSupportFragmentManager(), END_DATE_PICKER_TAG);
break;
The DatePickerFragment class:
public class DatePickerFragment extends DialogFragment {
#NonNull
#Override
public Dialog onCreateDialog(#Nullable Bundle savedInstanceState) {
Calendar calendar = Calendar.getInstance();
int year = calendar.get(Calendar.YEAR);
int month = calendar.get(Calendar.MONTH);
int day = calendar.get(Calendar.DAY_OF_MONTH);
return new DatePickerDialog(getActivity(), (DatePickerDialog.OnDateSetListener) getActivity(), year, month, day );
}
and this is how I get the result in the main activity
#Override
public void onDateSet(DatePicker view, int year, int month, int dayOfMonth) {
if (view.getTag().equals(START_DATE_PICKER_TAG)) {
calendarStartDate.set(Calendar.YEAR, year);
calendarStartDate.set(Calendar.MONTH, month);
calendarStartDate.set(Calendar.DAY_OF_MONTH, dayOfMonth);
start_date_btn.setText(dayOfMonth + "/" + (month + 1) + "/" + year);
} else {
calendarEndDate.set(Calendar.YEAR, year);
calendarEndDate.set(Calendar.MONTH, month);
calendarEndDate.set(Calendar.DAY_OF_MONTH, dayOfMonth);
end_date_btn.setText(dayOfMonth + "/" + (month + 1) + "/" + year);
}
}
However, I get a nullPointerException doing view.getTag(). How can I solve this, or how else can I diferentiate the results?
Aclaration: DatePickerDialog is a native class, not one which I created, so I can't edit their methods`
TimePickerFragment:
public class TimePickerFragment extends DialogFragment {
private static final String ARGS_TAG = "ARGS_TAG";
#NonNull
#Override
public Dialog onCreateDialog(#Nullable Bundle savedInstanceState) {
Calendar calendar = Calendar.getInstance();
int hour = calendar.get(Calendar.HOUR_OF_DAY);
int minute = calendar.get(Calendar.MINUTE);
final String tag = getArguments().getString(ARGS_TAG);
return new TimePickerDialog(getActivity(), (TimePickerDialog.OnTimeSetListener) getActivity(), hour, minute, android.text.format.DateFormat.is24HourFormat(getActivity())) {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
};
}
public static TimePickerFragment newInstance(String tag){
Bundle args = new Bundle();
args.putString(ARGS_TAG, tag);
TimePickerFragment fragment = new TimePickerFragment();
fragment.setArguments(args);
return fragment;
}
Solution: Define two interface to forward data from fragments to activity.
Step 1. Define OnDateSetListener interface to communicate between MainActivity and DatePickerFragment.
public interface OnDateSetListener {
void onDateSet(String tag, DatePicker view, int year, int month, int dayOfMonth);
}
Step 2. Define OnTimeSetListener interface to communicate between MainActivity and TimePickerFragment.
public interface OnTimeSetListener {
void onTimeSet(String tag, TimePicker view, int hourOfDay, int minute);
}
Step 3. Let MainActivity implements both of interfaces.
public class MainActivity extends AppCompatActivity implements OnDateSetListener, OnTimeSetListener {
// Your code her
...
#Override
public void onDateSet(String tag, DatePicker view, int year, int month, int dayOfMonth) {
// Process code with tag here
}
#Override
public void onTimeSet(String tag, TimePicker view, int hourOfDay, int minute) {
// Process code with tag here.
}
}
Step 4. Change code in DatePickerFragment
public class DatePickerFragment extends DialogFragment implements DatePickerDialog.OnDateSetListener {
private static final String ARGUMENT_TAG = "ARGUMENT_TAG";
public static DatePickerFragment newInstance(String tag) {
Bundle args = new Bundle();
args.putString(ARGUMENT_TAG, tag);
DatePickerFragment fragment = new DatePickerFragment();
fragment.setArguments(args);
return fragment;
}
#NonNull
#Override
public Dialog onCreateDialog(#Nullable Bundle savedInstanceState) {
Calendar calendar = Calendar.getInstance();
int year = calendar.get(Calendar.YEAR);
int month = calendar.get(Calendar.MONTH);
int day = calendar.get(Calendar.DAY_OF_MONTH);
return new DatePickerDialog(requireActivity(), this, year, month, day);
}
#Override
public void onDateSet(DatePicker view, int year, int month, int dayOfMonth) {
final String tag = getArguments().getString(ARGUMENT_TAG);
OnDateSetListener listener = (OnDateSetListener) requireActivity();
listener.onDateSet(tag, view, year, month, dayOfMonth);
}
}
Step 5. Change code in TimePickerFragment.
public class TimePickerFragment extends DialogFragment implements TimePickerDialog.OnTimeSetListener {
private static final String ARGS_TAG = "ARGS_TAG";
public static TimePickerFragment newInstance(String tag) {
Bundle args = new Bundle();
args.putString(ARGS_TAG, tag);
TimePickerFragment fragment = new TimePickerFragment();
fragment.setArguments(args);
return fragment;
}
#Override
public Dialog onCreateDialog(#Nullable Bundle savedInstanceState) {
Calendar calendar = Calendar.getInstance();
int hour = calendar.get(Calendar.HOUR_OF_DAY);
int minute = calendar.get(Calendar.MINUTE);
return new TimePickerDialog(requireActivity(), this, hour, minute, DateFormat.is24HourFormat(getActivity()));
}
#Override
public void onTimeSet(TimePicker view, int hourOfDay, int minute) {
final String tag = getArguments().getString(ARGS_TAG);
OnTimeSetListener listener = (OnTimeSetListener) requireActivity();
listener.onTimeSet(tag, view, hourOfDay, minute);
}
}
As I see, you've set the tag to the Fragment, but what you're trying to get is the tag of the View. They are not the same thing, as a view's tag is an object, while a fragment's tag is a string.
As you can see your view in onDateSet is a DatePicker, and you set your tag on the fragment containing the DatePicker, which is the DatePickerDialog.
So to get your tag you should try something like:
#Override
public void onDateSet(DatePicker view, int year, int month, int dayOfMonth) {
if (view.getParent() != null && view.getParent().getTag().equals(START_DATE_PICKER_TAG)) {
calendarStartDate.set(Calendar.YEAR, year);
calendarStartDate.set(Calendar.MONTH, month);
calendarStartDate.set(Calendar.DAY_OF_MONTH, dayOfMonth);
start_date_btn.setText(dayOfMonth + "/" + (month + 1) + "/" + year);
} else {
calendarEndDate.set(Calendar.YEAR, year);
calendarEndDate.set(Calendar.MONTH, month);
calendarEndDate.set(Calendar.DAY_OF_MONTH, dayOfMonth);
end_date_btn.setText(dayOfMonth + "/" + (month + 1) + "/" + year);
}
}
I am kind of stuck on my project. I am asking for help on the datepicker format I managed to display my one on a TextView in full format.
However, after doing some coding in java, when I call in a date picker and pick a new date, it updates in short format, for example.
Current date Friday, January, 20 2017 after using date picker it shows 20-1-17
I want it to display in full, please help, below is my Java code
public class EntryEdit extends AppCompatActivity {
TextView textView;
int year_x, month_x, day_x;
static final int DIALOG_ID = 0;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_entry_edit);
final Calendar cal = Calendar.getInstance();
year_x = cal.get(Calendar.YEAR);
month_x = cal.get(Calendar.MONTH);
day_x = cal.get(Calendar.DAY_OF_MONTH);
showDialogOnTextViewClick();
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
String currentDateString = DateFormat.getDateInstance(DateFormat.FULL).format(new Date());
TextView textView = (TextView) findViewById(R.id.date);
textView.setText(currentDateString);
}
public void showDialogOnTextViewClick() {
textView = (TextView) findViewById(R.id.date);
textView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
showDialog(DIALOG_ID);
}
});
}
#Override
protected Dialog onCreateDialog(int id) {
if (id == DIALOG_ID)
return new DatePickerDialog(this, dpickerListener, year_x, month_x, day_x);
return null;
}
private DatePickerDialog.OnDateSetListener dpickerListener
= new DatePickerDialog.OnDateSetListener() {
#Override
public void onDateSet(DatePicker view, int year, int month, int dayOfMonth) {
year_x = year;
month_x = month +1;
day_x = dayOfMonth;
String currentDateString = DateFormat.getDateInstance(DateFormat.FULL).format(new Date());
updateStartDisplay();
}
};
private void updateStartDisplay() {
textView.setText(new StringBuilder()
// Month is 0 based so add 1
.append(day_x + 1).append("-").append(month_x).append("-")
.append(year_x).append(" "));
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu2, menu);
return true;
}
The reason why your textView shows 20-1-2017 is because each time you pick a date in a DatePicker, you call updateStartDisplay() method, where you specifically set the text to be day-month-year.
Here's one possible solution:
private DatePickerDialog.OnDateSetListener dpickerListener
= new DatePickerDialog.OnDateSetListener() {
#Override
public void onDateSet(DatePicker view, int year, int month, int dayOfMonth) {
year_x = year;
month_x = month;
day_x = dayOfMonth;
Calendar calendar = Calendar.getInstance();
calendar.set(year_x, month_x, day_x);
String currentDateString = DateFormat.getDateInstance(DateFormat.FULL).format(calendar.getTime());
textView.setText(currentDateString);
}
};
I am trying to make the date picker appear in a dialog fragment upon clicking the date field to write/set the date I selected with the use of the DatePicker. Unfortunately, each time I click, the DatePicker doesn't show up.
Below is the the code of the class:
public class UpdateGrade extends DialogFragment{
private EditText dateField;
static final int DATE_DIALOG_ID = 0;
protected Dialog onCreateDialog(int id) {
Calendar c = Calendar.getInstance();
int cyear = c.get(Calendar.YEAR);
int cmonth = c.get(Calendar.MONTH);
int cday = c.get(Calendar.DAY_OF_MONTH);
switch (id) {
case DATE_DIALOG_ID:
return new DatePickerDialog(getActivity(), mDateSetListener, cyear, cmonth, cday);
}
return null;
}
private DatePickerDialog.OnDateSetListener mDateSetListener = new DatePickerDialog.OnDateSetListener() {
public void onDateSet(DatePicker view, int year, int monthOfYear, int dayOfMonth) {
String date_selected =String.valueOf(monthOfYear+1)+"-"+String.valueOf(dayOfMonth)+"-"+String.valueOf(year);
dateField.setText(date_selected);
}
};
#SuppressLint("SimpleDateFormat")
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.update_grade_layout, container);
getDialog().getWindow().requestFeature(STYLE_NO_TITLE);
dateField = (EditText) view.findViewById(R.id.dateField);
dateField.setOnTouchListener(new OnTouchListener(){
#SuppressWarnings("deprecation")
#Override
public boolean onTouch(View v, MotionEvent event) {
// TODO Auto-generated method stub
if(v == dateField)
getActivity().showDialog(DATE_DIALOG_ID);
return false;
}
});
return view;
}
Thank you!
You have to define the onCreateDialog() method to return an instance of DatePickerDialog:
public static class DatePickerFragment extends DialogFragment
implements DatePickerDialog.OnDateSetListener {
#Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
// Use the current date as the default date in the picker
final Calendar c = Calendar.getInstance();
int year = c.get(Calendar.YEAR);
int month = c.get(Calendar.MONTH);
int day = c.get(Calendar.DAY_OF_MONTH);
// Create a new instance of DatePickerDialog and return it
return new DatePickerDialog(getActivity(), this, year, month, day);
}
public void onDateSet(DatePicker view, int year, int month, int day) {
// Do something with the date chosen by the user
}
}
More information here.