Date Picker In Edit Text - What's wrong in this code? - java

I tried running it, but the Edit Text View gave no respond on clicking. The Date Picker was not even opened. What is wrong in here?
Please do help me with an elaborated answer along with the full code since I'm a newbie. Thanks
XML
<EditText
android:id="#+id/add_date"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginStart="32dp"
android:layout_marginLeft="32dp"
android:layout_marginTop="16dp"
android:ems="10"
android:hint="Enter Date"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="#+id/add" />
MainActivity
public class addScreen extends AppCompatActivity {
EditText dateFormat;
int year, month, day;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.add_screen);
{
dateFormat = findViewById(R.id.add_date);
final Calendar calendar = Calendar.getInstance();
dateFormat.setOnClickListener(v -> {
year = calendar.get(Calendar.YEAR);
month = calendar.get(Calendar.MONTH);
day = calendar.get(Calendar.DAY_OF_MONTH);
DatePickerDialog datePickerDialog = new DatePickerDialog(addScreen.this, (view, year, month, dayOfMonth) -> dateFormat.setText(SimpleDateFormat.getDateInstance().format(calendar.getTime())), year, month, day);
datePickerDialog.show();
});
}
}
}

As Ben P said in the comment above, EditText is focusable by default.
So if you want to stop it from being shown the keyboard and just listen to the click listener you may need to stop the focus this below line do this so add it EditText declaration in your xml
android:focusable="false"
and that's it your EditText now can listen to your click listener.
P.S. I would recommend for you to use the material TextInputLayout and TextInputEditText which has a great look and follows the modern UX when it comes to create and input field and shown it to your users.

Related

How to initialise Android DatePicker by Intent?

I've got a list of elements displayed. When I click on one element, a detail view is opening and displaying name, description etc. Also a date shall be changeable in the detail view.
For now, the date is set to today's date when I click, but the DatePicker does not show up (init method fails). I know I am doing something wrong and that there has to be an intent/an activity to start from my DetailView class, since it's not the MainActivity. But unfortunately, I have no idea how to do it.
This is my code in DetailView.java:
public void onDateChange() {
initDatePicker();
dateButton = findViewById(R.id.itemDateButton);
dateButton.setText(getTodaysDate());
}
private String getTodaysDate() {
Calendar cal = Calendar.getInstance();
int year = cal.get(Calendar.YEAR);
int month = cal.get(Calendar.MONTH);
month = month + 1;
int day = cal.get(Calendar.DAY_OF_MONTH);
return makeDateString(day, month, year);
}
private void initDatePicker() {
DatePickerDialog.OnDateSetListener dataSetListener = new DatePickerDialog.OnDateSetListener() {
#Override
public void onDateSet(DatePicker view, int year, int month, int dayOfMonth) {
month = month + 1;
String date = makeDateString(dayOfMonth, month, year);
dateButton.setText(date);
}
};
Calendar cal = Calendar.getInstance();
int year = cal.get(Calendar.YEAR);
int month = cal.get(Calendar.MONTH);
int day = cal.get(Calendar.DAY_OF_MONTH);
int style = AlertDialog.THEME_HOLO_LIGHT;
datePickerDialog = new DatePickerDialog(this, style, dataSetListener, year, month, day);
}
public void openDatePicker(View view) {
datePickerDialog.show();
}
The xml:
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/itemDateText"
android:layout_marginTop="16dp"
android:layout_marginBottom="16dp"
android:text="Date"
app:layout_constraintTop_toBottomOf="#id/itemDescriptionWrapper"
/>
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/itemDateButton"
android:text="Change date"
style="?android:spinnerStyle"
app:layout_constraintTop_toBottomOf="#id/itemDateText"
android:onClick="#{() -> controller.onDateChange()}"
/>
I'm also able to send mails and sms from the DetailView by intent. But i just don't know how to start a DatePicker intent.
Any ideas? I would be very grateful. :)
Best regards,
Jess
To show the DatePicker, All you require is to add .show() method of DatePickerDialog inside your initDatePicker() function.
datePickerDialog = new DatePickerDialog(this, style, dataSetListener, year, month, day);
datePickerDialog.show();

DatePicker dialog not working propely and not looking nice

I am trying to use a DatePicker:
My code is:
DatePicker datePicker = (DatePicker) v.findViewById(R.id.dialog_date_datePicker);
datePicker.init(year, month, day, new OnDateChangedListener() {
#Override
public void onDateChanged(DatePicker view, int year, int month,
int day) {
mDate = new GregorianCalendar(year, month, day).getTime();
getArguments().putSerializable(EXTRA_DATE, mDate);
}
});
But when I select a date the onDateChanged method is never called. After googling I found that if I changed my date picker layout to include: android:datePickerMode="spinner" /> and remove android:calendarViewShown="false" the onDateChanged is called and the code works but the date picker dialog is really bad looking.
My layout is:
<DatePicker xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/dialog_date_datePicker"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="vertical"
android:datePickerMode="spinner" />
<!-- android:calendarViewShown="false" -->
So why is the calenderViewShown attribute causing a problem and how can I improve the look of the date picker UI dialog?
If you want to use datepicker dialog than there's no need to use DatePicker just do it this way:
Calendar c = Calendar.getInstance();
DatePickerDialog datePickerDialog = new DatePickerDialog(SignUpActivity.this, android.R.style.Theme_Holo_Light_Dialog_MinWidth, new OnDateSetListener() {
#Override
public void onDateSet(DatePicker view, int year, int monthOfYear, int dayOfMonth) {
// TODO Auto-generated method stub
try {
Date d = new SimpleDateFormat("yyyy-MM-dd", Locale.getDefault()).parse(year+"-"+(monthOfYear+1)+"-"+dayOfMonth);
} catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
}
}
}, c.get(Calendar.YEAR), c.get(Calendar.MONTH), c.get(Calendar.DAY_OF_MONTH));
datePickerDialog.getDatePicker().setCalendarViewShown(false);
datePickerDialog.getWindow().setBackgroundDrawableResource(android.R.color.transparent);
datePickerDialog.show();
You can also use this library : Beautiful DatePicker UI
If on AS, add this in dependencies : compile 'com.github.flavienlaurent.datetimepicker:library:0.0.2'
Also,as pointed at this question : Datepicker
You can use this to solve the issue.
<DatePicker xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/dialog_date_datePicker"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:calendarViewShown="false"
android:datePickerMode="spinner" >
</DatePicker>

How to set maximum and minimum date for datepicker in android

I am using a tutorial i found on the net for datepicker.But i want to set the maximum and minimum date for the datepicker.Also i have heard that there is an issue for API level less than 11.
My code:
package com.androidexample.datepicker;
import java.util.Calendar;
import android.app.Activity;
import android.app.DatePickerDialog;
import android.app.Dialog;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.TextView;
public class DatePickerExample extends Activity {
private TextView Output;
private Button changeDate;
private int year;
private int month;
private int day;
static final int DATE_PICKER_ID = 1111;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
Output = (TextView) findViewById(R.id.Output);
changeDate = (Button) findViewById(R.id.changeDate);
// Get current date by calender
final Calendar c = Calendar.getInstance();
year = c.get(Calendar.YEAR);
month = c.get(Calendar.MONTH);
day = c.get(Calendar.DAY_OF_MONTH);
// Show current date
Output.setText(new StringBuilder()
// Month is 0 based, just add 1
.append(month + 1).append("-").append(day).append("-")
.append(year).append(" "));
// Button listener to show date picker dialog
changeDate.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// On button click show datepicker dialog
showDialog(DATE_PICKER_ID);
}
});
}
#Override
protected Dialog onCreateDialog(int id) {
switch (id) {
case DATE_PICKER_ID:
// open datepicker dialog.
// set date picker for current date
// add pickerListener listner to date picker
return new DatePickerDialog(this, pickerListener, year, month,day);
}
return null;
}
private DatePickerDialog.OnDateSetListener pickerListener = new DatePickerDialog.OnDateSetListener() {
// when dialog box is closed, below method will be called.
#Override
public void onDateSet(DatePicker view, int selectedYear,
int selectedMonth, int selectedDay) {
year = selectedYear;
month = selectedMonth;
day = selectedDay;
// Show selected date
Output.setText(new StringBuilder().append(month + 1)
.append("-").append(day).append("-").append(year)
.append(" "));
}
};
}
The xml code:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical" >
<Button
android:id="#+id/changeDate"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Click To Change Date" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Current/Selected Date (M-D-YYYY): "
android:textAppearance="?android:attr/textAppearanceLarge" />
<TextView
android:id="#+id/Output"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text=""
android:textAppearance="?android:attr/textAppearanceLarge" />
</LinearLayout>
The problem with the above code is that there is no upper limit on the year part.I also need a lower limit on the year part.Can someone tell me as how to modify the code to set the upper and lower limit on the year part?
In DatePickerDialog.OnDateSetListener() you can compare the month, year , date with your specified min and max dates.
You can obtain DatePicker using DatePickerDialog.
DatePickerDialog dialog = new DatePickerDialog(this, pickerListener, year, month,day);
//calculate min and max dates (you can use, Calender API or Joda Time, just search for it.
dialog.getDatePicker().setMaxDate(maxDate.getTime());
dialog.getDatePicker().setMinDate(minDate.getTime());
return dialog;
You can get the underlying DatePicker from a DatePickerDialog by simply calling getDatePicker() and set its bounds using:
setMinDate(long minDate)
setMaxDate(long maxDate)
This works only for API level 11 and above.

How to create a textedit for date only programatically in android?

I want to create a textedit field where the user enters a date only (no time). The date will get stored in MY SQL. Whats the best way to do this with the least amount of validation? Is there like a built in textfield for dates that keeps it in the proper format?
I have this:
public static void AddEditTextDate(Context context, LinearLayout linearlayout, String text, int id) {
EditText edittext = new EditText(context);
edittext.setInputType(InputType.TYPE_DATETIME_VARIATION_DATE);
edittext.setText(text);
edittext.setId(id);
LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(LayoutParams.MATCH_PARENT,LayoutParams.WRAP_CONTENT);
edittext.setLayoutParams(params);
linearlayout.addView(edittext);
}
But when I try to type in it, it looks like a normal keyboard. I would expect it to go into the number pad by default or something...
EDIT: It needs to work with android 2.1+ (i.e. v7)
Does anyone know?
Thanks
You said Whats the best way to do this with the least amount of validation? Is there like a built in textfield for dates that keeps it in the proper format?
There is one way which comes to my mind, using which you might not need to check any validation of the date format that user entered. You can call a DatePickerDialog on click of your EditText box. Then user can choose the date using that. After user has chosen the date you can update your EditText with the chosen date. This way you lesses the effort of validation of the date format entered and user can easily and intuitively choose the date. You might so something like:
Calendar myCalendar = Calendar.getInstance();
DatePickerDialog.OnDateSetListener date = new DatePickerDialog.OnDateSetListener() {
#Override
public void onDateSet(DatePicker view, int year, int monthOfYear,
int dayOfMonth) {
myCalendar.set(Calendar.YEAR, year);
myCalendar.set(Calendar.MONTH, monthOfYear);
myCalendar.set(Calendar.DAY_OF_MONTH, dayOfMonth);
updateLabel();
}
};
//When the editText is clicked then popup the DatePicker dialog to enable user choose the date
edittext.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
new DatePickerDialog(new_split.this, date, myCalendar
.get(Calendar.YEAR), myCalendar.get(Calendar.MONTH),
myCalendar.get(Calendar.DAY_OF_MONTH)).show();
}
});
// Call this whn the user has chosen the date and set the Date in the EditText in format that you wish
private void updateLabel() {
String myFormat = "MM/dd/yyyy"; //In which you need put here
SimpleDateFormat sdf = new SimpleDateFormat(myFormat, Locale.US);
edittext.setText(sdf.format(myCalendar.getTime()));
}
Source: This answer on Datepicker: How to popup datepicker when click on edittext question. Hope this helps.

How to make a date spinner on Android

How do I create an Android spinner that open a date picker dialog?
I want a Spinner that looks like the one in the calendar app, as shown in the screenshot below.
What I've already tried:
I made a spinner in my layout XML and tried to set the onclick attribute to call a method that shows the dialog. When I put a method name in "on click", I got and error that says "The following classes could not be found:
- Spinner (Change to android.widget.Spinner, Fix Build Path, Edit XML)".
<Spinner
android:id="#+id/spinner1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:onClick="showDatePickerDialog" />
showDatePickerDialog is in the right class:
public void showDatePickerDialog(View v) {
DialogFragment newFragment = new DatePickerFragment();
newFragment.show(getFragmentManager(), "Date");
}
And this is DatePickerFragment (copied from another website):
import java.util.Calendar;
import android.app.DatePickerDialog;
import android.app.Dialog;
import android.app.DialogFragment;
import android.os.Bundle;
import android.widget.DatePicker;
public 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
}
}
SOLUTION:
I found the solution at another question.
I used a regular spinner in the layout file, then in my activity class, has this code:
dateSpinner = (Spinner)findViewById(R.id.spinner_date);
View.OnTouchListener Spinner_OnTouch = new View.OnTouchListener() {
public boolean onTouch(View v, MotionEvent event) {
if (event.getAction() == MotionEvent.ACTION_UP) {
showDatePickerDialog(v);
}
return true;
}
};
View.OnKeyListener Spinner_OnKey = new View.OnKeyListener() {
public boolean onKey(View v, int keyCode, KeyEvent event) {
if (keyCode == KeyEvent.KEYCODE_DPAD_CENTER) {
showDatePickerDialog(v);
return true;
}
else {
return false;
}
}
};
dateSpinner.setOnTouchListener(Spinner_OnTouch);
dateSpinner.setOnKeyListener(Spinner_OnKey);
It seems a little hacked, but it works. Does anyone know a cleaner way to do it? It would not let me setOnClickListener() or setOnItemClickListener() on the spinner.
I was able to achieve it very easily. It looks exactly like that of the calendar app :)
Use a TextView and give it a spinner style:
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
style="#android:style/Widget.Holo.Spinner" />
For API 10 and below without the Holo Theme, use:
style="#android:style/Widget.Spinner"
I think in general what people do in this case is use a button and style it like a spinner (an approach here, I think a better approach, mostly just setting the style to android.R.attr.spinnerStyle), or they use a spinner but overload the click action to create a dialog.
Of course the hard part there is creating the custom dialog that has nice month/day/year spin-ie-things (they aren't spinners... they are kind of like slot machines or something) in them!
There's a few ways you can go about that, there is some google documentation here, and you can always just lift the android source code (although there are obviously drawbacks).
A button is the best way, you just need to change the button style.
I tried to set the default android spinner style to my button, but it doesn't work correctly.
So I made my own style (it's a copy of the default spinner style). Here it is:
`<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:state_enabled="false"
android:drawable="#drawable/spinner_disabled_holo_light" />
<item android:state_pressed="true"
android:drawable="#drawable/spinner_pressed_holo_light" />
<item android:state_pressed="false" android:state_focused="true"
android:drawable="#drawable/spinner_focused_holo_light" />
<item android:drawable="#drawable/spinner_default_holo_light" />
</selector>
`
The images you will find in ..\sdk\platforms\android-%%\data\res\drawable.
This works fine for me. This is a simple way to make a button spinner style, like the spinner on Google Calendar.

Categories

Resources