I'm a beginning android developer.
I need to pass data from two date pickers and a spinner to another activity.
Can some one help me with this code:
package qi.com;
import java.text.DateFormat;
import java.util.Calendar;
import android.app.Activity;
import android.app.DatePickerDialog;
import android.app.DatePickerDialog.OnDateSetListener;
import android.app.Dialog;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;
//multi date input
public class CoaActivity extends Activity implements AdapterView.OnItemSelectedListener {
TextView selection;
TextView mDateStart;
TextView mDateEnd;
Button mPickStart;
Button mPickEnd;
Calendar startDate;
Calendar EndDate;
int mYear;
int mMonth;
int mDay;
//list menu
String[] items = {"Pendapatan","Biaya"};
static final int DATE_DIALOG_ID = 0;
private TextView activeDateDisplay;
private Calendar activeDate;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
//display to text view from list View
selection = (TextView) findViewById(R.id.selection);
Spinner spin= (Spinner) findViewById(R.id.spinner);
spin.setOnItemSelectedListener(this);
ArrayAdapter<String> aa= new ArrayAdapter<String> (this, android.R.layout.simple_spinner_item, items);
aa.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spin.setAdapter(aa);
//capture view elements
mDateStart = (TextView) findViewById(R.id.DateStar);
mPickStart = (Button) findViewById(R.id.btn_PickDateStart);
//current date
startDate = Calendar.getInstance();
//listener click button
mPickStart.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
showDateDialog(mDateStart, startDate);
}
});
//END Date
mDateEnd = (TextView) findViewById(R.id.DateEnd);
mPickEnd = (Button) findViewById(R.id.btn_PickDateEnd);
EndDate = Calendar.getInstance();
//listener click button
mPickEnd.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
showDateDialog(mDateEnd, EndDate);
}
});
//display current date
updateDisplay(mDateStart, startDate);
updateDisplay(mDateEnd, EndDate);
//Detail("tes");
}
private void updateDisplay(TextView dateDisplay, Calendar date) {
dateDisplay.setText(
new StringBuilder()
// Month is 0 based so add 1
//.append(date.get(Calendar.DAY_OF_MONTH)).append("-")
.append(date.get(Calendar.DATE)).append("-")
.append(date.get(Calendar.MONTH) + 1).append("-")
.append(date.get(Calendar.YEAR)).append(" "));
//.append(DateFormat.getDateInstance(Calendar.MONTH)));
}
public void showDateDialog(TextView dateDisplay, Calendar date) {
activeDateDisplay = dateDisplay;
activeDate = date;
showDialog(DATE_DIALOG_ID);
}
private OnDateSetListener dateSetListener = new OnDateSetListener() {
#Override
public void onDateSet(DatePicker view, int year, int monthOfYear, int dayOfMonth) {
activeDate.set(Calendar.YEAR, year);
activeDate.set(Calendar.MONTH, monthOfYear);
//activeDate.set(Calendar.DAY_OF_MONTH, dayOfMonth);
activeDate.set(Calendar.DATE, dayOfMonth);
updateDisplay(activeDateDisplay, activeDate);
unregisterDateDisplay();
}
};
private void unregisterDateDisplay() {
activeDateDisplay = null;
activeDate = null;
}
protected Dialog onCreateDialog(int id) {
switch (id) {
case DATE_DIALOG_ID:
return new DatePickerDialog(this, dateSetListener, activeDate.get(Calendar.YEAR), activeDate.get(Calendar.MONTH), activeDate.get(Calendar.DATE));
}
return null;
}
protected void onPrepareDialog(int id, Dialog dialog) {
super.onPrepareDialog(id, dialog);
switch (id) {
case DATE_DIALOG_ID:
((DatePickerDialog) dialog).updateDate(activeDate.get(Calendar.YEAR), activeDate.get(Calendar.MONTH), activeDate.get(Calendar.DATE));
break;
}
}
public void onItemSelected(AdapterView<?> parent, View v, int position, long id) {
selection.setText(items[position]);
Intent grid=new Intent(this, Grid.class);
this.startActivity(grid);
//send to another activity
//Detail(items[position]);
}
public void onNothingSelected(AdapterView<?> parent) {
selection.setText("");
}
//another activity
public void Detail(String id)
//public void Detail()
{
//Intent detail=new Intent(con, Detail.class);
Intent grid=new Intent(this, Grid.class);
grid.putExtra("IDP", id);
this.startActivity(grid);
//Toast.makeText(this, "list : " , Toast.LENGTH_SHORT).show();
}
}
This is the xml file:
<?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" >
<TextView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="Mulai dari :" />
<TextView
android:id="#+id/DateStar"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="" />
<Button
android:id="#+id/btn_PickDateStart"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="Tanggal Awal" />
<TextView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="Sampai dengan :" />
<TextView
android:id="#+id/DateEnd"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="" />
<Button
android:id="#+id/btn_PickDateEnd"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="Tanggal Akhir" />
<TextView
android:id="#+id/selection"
android:layout_width="fill_parent"
android:layout_height="wrap_content"/>
<Spinner
android:id="#+id/spinner"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:drawSelectorOnTop="false" />
</LinearLayout>
Use the long value that Date gives you, and put it in the extras, along with everything else you are sending to the activity.
Related
I am using a single button to do two task.
1.Date Selection
2.Difference between two dates
As-is:
I am using 'onclick' method for two button.
btnDate2 using to select the date and onclick is(setDate2)
button9 using to calculate the difference between two dates and onclick is(diff)
To-be:
One button for selecting the date and calculate the difference between two dates.And it should be in sequence.ex:
1: Select date
2. Calculate the difference between dates
Current code:
MainActivity.java
package com.bar.example.myapplication;
import android.app.DialogFragment;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.text.format.DateFormat;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import org.threeten.bp.LocalDate;
import org.threeten.bp.format.DateTimeFormatter;
import org.threeten.bp.format.DateTimeParseException;
import org.threeten.bp.temporal.ChronoUnit;
import java.text.SimpleDateFormat;
public class MainActivity extends AppCompatActivity {
public TextView txtResult, tv, textDivNumber, textAVG, txtZaMisiac;
public static TextView tvresult;
public Button reset, button, button1, button2, button9, editTextDate3, editTextDate5, btnok;
public EditText barcodeResult;
public static EditText courseTitleEditText;
private ListView offeringsListView;
private static DateTimeFormatter dateFormatter = DateTimeFormatter.ofPattern("d.M.uuuu");
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
editTextDate5 = (Button) findViewById(R.id.editText5);
button2 = (Button) findViewById(R.id.btnDate2);
txtResult = (TextView) findViewById(R.id.editText2);
editTextDate5.setText(DateFormat.format("dd.MM.yyyy", new java.util.Date()).toString());
}
public void diff(View view) {
SimpleDateFormat myFormat = new SimpleDateFormat("dd.MM.yyyy");
CharSequence inputString1 = editTextDate5.getText();
try {
LocalDate date1 = LocalDate.parse(inputString1, dateFormatter);
CharSequence inputString2 = button2.getText();
try {
LocalDate date2 = LocalDate.parse(inputString2, dateFormatter);
long diffDate = ChronoUnit.DAYS.between(date1, date2);
txtResult.setText(String.valueOf(diffDate));
} catch (DateTimeParseException dtpe) {
Toast.makeText(this, "Date2 is not a valid date: " + inputString2, Toast.LENGTH_SHORT).show();
}
} catch (DateTimeParseException dtpe) {
Toast.makeText(this, "Date1 is not a valid date: " + inputString1, Toast.LENGTH_SHORT).show();
}
}
public void setDate1(View view) {
DialogFragment newFragment = new DatePickerFragment();
newFragment.show(getFragmentManager(), "Date Picker");
}
public void setDate2(View view) {
DialogFragment newFragment = new DatePickerFragment2();
newFragment.show(getFragmentManager(), "Date Picker");
}
#Override
public void onPointerCaptureChanged(boolean hasCapture) {
}
}
Datepickerformat2.java
package com.bar.example.myapplication;
import android.app.DatePickerDialog;
import android.app.Dialog;
import android.app.DialogFragment;
import android.os.Bundle;
import android.widget.Button;
import android.widget.DatePicker;
import java.util.Calendar;
public class DatePickerFragment2 extends DialogFragment implements DatePickerDialog.OnDateSetListener {
#Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
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);
return new DatePickerDialog(getActivity(), this, year, month, day);
}
public void onDateSet(DatePicker view, int year, int month, int day) {
Button btnDate2 = (Button) getActivity().findViewById(R.id.btnDate2);
String stringOfDate = day + "." + (month + 1) + "." + year;
btnDate2.setText(stringOfDate);
}
}
activity_main.xml
<?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">
<LinearLayout android:layout_width="match_parent" android:layout_height="wrap_content" android:orientation="horizontal" android:weightSum="1">
<TextView android:id="#+id/editText1" android:layout_width="47dp" android:layout_height="wrap_content" android:ems="10" android:inputType="textNoSuggestions" android:text="Date:" />
<Button android:id="#+id/editText5" android:layout_width="47dp" android:layout_height="wrap_content" android:layout_weight="0.50" android:ems="10" android:inputType="textNoSuggestions" android:text="" />
<TextView android:id="#+id/editText2" android:layout_width="49dp" android:layout_height="wrap_content" android:ems="10" android:inputType="textNoSuggestions" android:text="Expiry:" />
<Button android:id="#+id/btnDate2" android:layout_width="59dp" android:layout_height="wrap_content" android:layout_weight="0.41" android:ems="10" android:onClick="setDate2" android:text="" />
<Button android:id="#+id/button9" android:layout_width="59dp" android:layout_height="wrap_content" android:layout_weight="0.41" android:ems="10" android:inputType="textNoSuggestions" android:onClick="diff" android:text="calc" />
</LinearLayout>
with amended code.
With 1st Click ,
After selecting ok.
Now again i should click the calc button to know the days difference.
What i need is 1st click the date and select "ok" upon choosing the date.i should be able to see the days difference upon clicking "ok" as per screen instead of pressing again the button.
Requirement 3:
When edittext2 number is exceeds vs spinner2 number then edittext2 color should change it to red color and some doast message
When edittext2 number is reaching to very near vs spinner2 number then edittext2 color should change it to yellow color and some doast message
1.Add below method into MainActivity.java:
public void dualFunctions(View view) {
if(view.getTag() == null) view.setTag("0");
if(view.getTag().equals("0")){
view.setTag("1");
view.setBackgroundColor(Color.GREEN);
setDate2(view);
}else{
view.setTag("0"); // Remove this line for one shoot.
view.setBackgroundColor(Color.YELLOW);
diff(view);
}
}
2.Change the button in layout to use this method.
The method toggles between date selection and calculation. If date selection is allowed for only once, then remove the line with comment.
Hope that helps!
Updated:
public void onDateSet(DatePicker view, int year, int month, int day) {
Button btnDate2 = (Button) getActivity().findViewById(R.id.btnDate2);
String stringOfDate = day + "." + (month + 1) + "." + year;
btnDate2.setText(stringOfDate);
MainActivity activity = (MainActivity)getActivity();
activity.diff(btnDate2);
}
For Requirement3:
Added if-else to check conditions.
private final static int VERY_NEAR_DATE = 30;
public void diff(View view) {
SimpleDateFormat myFormat = new SimpleDateFormat("dd.MM.yyyy");
CharSequence inputString1 = editTextDate5.getText();
try {
LocalDate date1 = LocalDate.parse(inputString1, dateFormatter);
CharSequence inputString2 = button2.getText();
try {
LocalDate date2 = LocalDate.parse(inputString2, dateFormatter);
long diffDate = ChronoUnit.DAYS.between(date1, date2);
txtResult.setText(String.valueOf(diffDate));
diffDate = (Long)ok2.getSelectedItem() - diffDate;
if(diffDate < 0){
txtResult.setTextColor(Color.RED);
Toast.makeText(this, "Date not allowed!!", Toast.LENGTH_SHORT).show();
}else if(diffDate < VERY_NEAR_DATE) {
txtResult.setTextColor(Color.YELLOW);
Toast.makeText(this, "Date too near!", Toast.LENGTH_SHORT).show();
}
} catch (DateTimeParseException dtpe) {
Toast.makeText(this, "Date2 is not a valid date: " + inputString2, Toast.LENGTH_SHORT).show();
}
} catch (DateTimeParseException dtpe) {
Toast.makeText(this, "Date1 is not a valid date: " + inputString1, Toast.LENGTH_SHORT).show();
}
}
If need to update views after selection changed in spinner, then add below code inside onCreate():
ok2.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
diff(null);
}
#Override
public void onNothingSelected(AdapterView<?> parent) {}
});
I have Set Two Date Pickers(Namely Check In and Check Out). For the first time when I run the app everything is fine,the date which I clicked is displayed in the TextView.But without running the app second time When I try to click the Check In button the date is not changing in the TextView. But the date is changing in the LogCat. At the same time the Check Out button is working fine for the first time and also with second time(without running the app again). Kindly solve my issue.
Here is my code :
import java.util.Calendar;
import android.app.Activity;
import android.app.DatePickerDialog;
import android.app.Dialog;
import android.os.Bundle;
import android.support.v7.app.ActionBarActivity;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.TextView;
import android.widget.Toast;
import java.util.Calendar;
public class MainActivity extends ActionBarActivity {
Button checkIn, checkOut, checkavailability;
TextView displayCheckIn, displayCheckOut;
int year, month, day;
static final int DATE_DIALOG_ID = 1;
static final int DATE_DIALOG_ID2 = 2;
int cur = 0;
String chidate, chodate;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
checkIn = (Button) findViewById(R.id.checkInBtn);
checkOut = (Button) findViewById(R.id.checkOutBtn);
displayCheckIn = (TextView) findViewById(R.id.displayCheckIntv);
displayCheckOut = (TextView) findViewById(R.id.displayCheckOuttv);
checkavailability = (Button) findViewById(R.id.checkAvailabilityBtn);
setCurrentDateOnView();//declaring a method to display the current date in the opening
addListenerOnButton();
}
//settin the current date in the opening page
public void setCurrentDateOnView() {
Calendar today = Calendar.getInstance();
year = today.get(Calendar.YEAR);
month = today.get(Calendar.MONTH);
day = today.get(Calendar.DAY_OF_MONTH);
//displaying current date in the check in textView
displayCheckIn.setText(year + "-" + (month + 1) + "-" + day);
//displaying the current date in check out textView by getting the text from the check in view
displayCheckOut.setText(year + "-" + (month + 1) + "-" + day);
}
public void addListenerOnButton() {
checkIn.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
showDialog(DATE_DIALOG_ID);
}
});
checkOut.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
showDialog(DATE_DIALOG_ID2);
}
});
checkavailability.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
//checkAvailability();
}
});
}
#Override
protected Dialog onCreateDialog(int id) {
switch (id) {
case DATE_DIALOG_ID:
System.out.println("onCreate Dialog :" + id);
cur = DATE_DIALOG_ID;
//Displaying the Date Picker Dialog on the screen with today's date
return new DatePickerDialog(this, datePickerListener, year, month, day);
case DATE_DIALOG_ID2:
System.out.println("onCreateDialog :" + id);
cur = DATE_DIALOG_ID2;
return new DatePickerDialog(this, datePickerListener, year, month, day);
}
return null;
}
private DatePickerDialog.OnDateSetListener datePickerListener = new DatePickerDialog.OnDateSetListener() {
#Override
public void onDateSet(DatePicker view, int syear, int monthOfYear, int dayOfMonth) {
year = syear;
month = monthOfYear;
day = dayOfMonth;
if (cur == DATE_DIALOG_ID) {
displayCheckIn.setText(year + "-" + (month + 1) + "-" + day);
chidate = displayCheckIn.getText().toString();
System.out.println(chidate);
//Toast.makeText(getApplicationContext(),chidate,Toast.LENGTH_LONG).show();
} else {
displayCheckOut.setText(year + "-" + (month + 1) + "-" + day);
chodate = displayCheckOut.getText().toString();
System.out.println(chodate);
//Toast.makeText(getApplicationContext(),chodate,Toast.LENGTH_LONG).show();
}
}
};
//This is the code which I want to check the Checkin date every time.
/*public void checkAvailability() {
String[] datesin = {"2014-12-16", "2014-12-17", "2014-12-18"};
for (int j = 0; j < datesin.length; j++) {
if (datesin[j].equals(chidate)) {
Toast.makeText(getApplicationContext(), "Room Not Available", Toast.LENGTH_LONG).show();
break;
} else
Toast.makeText(getApplicationContext(), "Room Available", Toast.LENGTH_LONG).show();
}
}*/
}
And My XML is :
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent"
android:layout_height="match_parent" android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
android:paddingBottom="#dimen/activity_vertical_margin" tools:context=".MainActivity"
>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/displayCheckIntv"
android:text="Hiiiiiiiiiiiiiiiiiiiii"
android:layout_toEndOf="#+id/datePicker"
android:layout_alignTop="#+id/datePicker"
android:layout_centerHorizontal="true" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="CheckIn"
android:id="#+id/checkInBtn"
android:layout_alignParentTop="true"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Check Out"
android:id="#+id/checkOutBtn"
android:layout_marginTop="48dp"
android:layout_below="#+id/checkInBtn"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Check Out"
android:id="#+id/displayCheckOuttv"
android:layout_toEndOf="#+id/checkOutBtn"
android:layout_alignBottom="#+id/checkOutBtn"
android:layout_centerHorizontal="true" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Check Availability"
android:id="#+id/checkAvailabilityBtn"
android:layout_centerVertical="true"
android:layout_alignLeft="#+id/displayCheckOuttv"
android:layout_alignStart="#+id/displayCheckOuttv" />
</RelativeLayout>
I have a search activity with two edit text fields. I like on edit text click date picker dialog to be show. However when I click on edit text, first the keyboard is shown, then after second click the date picker dialog is shown. Could somebody help me?
Here is activity code
package com.example.firstdemoapp.activities;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Locale;
import com.example.firstdemoapp.R;
import com.example.firstdemoapp.model.StatusDK;
import android.app.Activity;
import android.app.DatePickerDialog;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.ArrayAdapter;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.Spinner;
public class SearchingTaxActivity extends Activity implements OnClickListener,
DatePickerDialog.OnDateSetListener, OnItemSelectedListener {
private Calendar calendarFrom;
private Calendar calendarTo;
private String myFormat;
private SimpleDateFormat sdf;
private EditText dateFrom;
private EditText dateTo;
private EditText activeEditText;
private Calendar activeCalendar;
private Spinner spinnerStatusDK;
private ArrayAdapter spinnerArrayAdapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_search_tax);
calendarFrom = Calendar.getInstance();
calendarTo = Calendar.getInstance();
myFormat="dd/MM/yyyy";
sdf = new SimpleDateFormat(myFormat, Locale.US);
dateFrom = (EditText) findViewById(R.id.dateFrom);
dateTo = (EditText) findViewById(R.id.dateTo);
spinnerStatusDK=(Spinner)findViewById(R.id.spinnerStatusDK);
spinnerArrayAdapter = new ArrayAdapter(this,
android.R.layout.simple_spinner_item, new StatusDK[] {
new StatusDK( 0, "0" ),
new StatusDK( 1, "1" ),
new StatusDK( 2, "2" ),
});
spinnerStatusDK.setAdapter(spinnerArrayAdapter);
spinnerStatusDK.setOnItemSelectedListener(this);
dateFrom.setOnClickListener(this);
dateTo.setOnClickListener(this);
}
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
if (v == dateFrom) {
activeCalendar = calendarFrom;
activeEditText = dateFrom;
} else if (v == dateTo) {
activeCalendar = calendarTo;
activeEditText = dateTo;
}
new DatePickerDialog(SearchingTaxActivity.this, this,
activeCalendar.get(Calendar.YEAR),
activeCalendar.get(Calendar.MONTH),
activeCalendar.get(Calendar.DAY_OF_MONTH)).show();
}
#Override
public void onDateSet(DatePicker view, int year, int monthOfYear,
int dayOfMonth) {
// TODO Auto-generated method stub
activeCalendar.set(Calendar.YEAR, year);
activeCalendar.set(Calendar.MONTH, monthOfYear);
activeCalendar.set(Calendar.DAY_OF_MONTH, dayOfMonth);
if (activeEditText != null) {
activeEditText.setText(sdf.format(activeCalendar.getTime()));
}
}
#Override
public void onItemSelected(AdapterView<?> arg0, View arg1, int arg2,
long arg3) {
// TODO Auto-generated method stub
}
#Override
public void onNothingSelected(AdapterView<?> arg0) {
// TODO Auto-generated method stub
}
}
and the layout for the activity is:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context="${relativePackage}.${activityClass}" >
<TextView android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="#string/dateFromTextView"
/>
<EditText
android:id="#+id/dateFrom"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:ems="10"
android:hint="#string/edit_datefrom"
/>
<TextView android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="#string/dateToTextView"
/>
<EditText
android:id="#+id/dateTo"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:ems="10"
android:hint="#string/edit_dateto"
/>
<Spinner
android:id="#+id/spinnerStatusDK"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
I added android:focusableInTouchMode="false" for edit text in the xml file and this helped me. Because first focus event is fired, and then click event is fired.
you can try to hide a keyboard using InputMethodManager class
private void hideKeyboard(EditText et) {
InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
imm.hideSoftInputFromWindow(et.getWindowToken(), 0);
}
This is best solution which is very useful for open any DatePicker & TimePicker Dialog from EditText,
editdate.setFocusable(false);
editdate.setKeyListener(null);
Ok so i have this app i'm working on... It has a left menu slide-out using ABS and the sliding menu lib. Here's my fragment that is launched once the menu item is selected. This fragment is suppose to have a text field to display the date you select and a button to select a date. Any idea's on what i'm doing wrong that SelectDateFragment is erroring?
Here's the XML layout:
<EditText
android:id="#+id/dateselected"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true"
android:layout_marginLeft="20dp"
android:layout_marginTop="56dp"
android:ems="10"
android:inputType="date" >
<requestFocus />
</EditText>
<Button
android:id="#+id/pickdate"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignBottom="#+id/dateselected"
android:layout_toRightOf="#+id/dateselected"
android:contentDescription="#string/selectdate"
android:cropToPadding="true"
android:onClick="selectDate"
android:src="#drawable/ic_datepicker" />
</RelativeLayout>
Here's the java class:
import java.util.Calendar;
import android.annotation.SuppressLint;
import android.app.DatePickerDialog;
import android.app.Dialog;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.support.v4.app.Fragment;
import android.support.v4.app.DialogFragment;
import android.widget.EditText;
public class DatePicker extends Fragment {
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstaceState){
return inflater.inflate(R.layout.fragment_charting, container, false);
}
EditText mEdit;
#Override
public void onStart() {
super.onStart();
}
public void selectDate(View view) {
DialogFragment newFragment = new SelectDateFragment();
newFragment.show(getFragmentManager(), "DatePicker");
}
public void populateSetDate(int year, int month, int day) {
mEdit = (EditText)getView().findViewById(R.id.dateselected);
mEdit.setText(month+"/"+day+"/"+year);
}
public class SelectDateFragment extends DialogFragment implements DatePickerDialog.OnDateSetListener {
#Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
final Calendar calendar = Calendar.getInstance();
int yy = calendar.get(Calendar.YEAR);
int mm = calendar.get(Calendar.MONTH);
int dd = calendar.get(Calendar.DAY_OF_MONTH);
return new DatePickerDialog(getActivity(), this, yy, mm, dd);
}
#Override
public void onDateSet(android.widget.DatePicker view, int year, int monthOfYear, int dayOfMonth) {
// TODO Auto-generated method stub
populateSetDate(year, monthOfYear, dayOfMonth);
}
}
}
EDIT:
I'm trying to follow http://javapapers.com/android/android-datepicker/
The error i'm getting is the fragment inner class should be static. I don't understand enough about this topic, and from reading more i still do not, to understand why his works and mine does not.
try this one
shipdate.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
showDialog(999);
}
});
#Override
protected Dialog onCreateDialog(int id) {
switch (id) {
case 999:
// set date picker as current date
return new DatePickerDialog(this, datePickerListener, year, month,
day);
}
return null;
}
private DatePickerDialog.OnDateSetListener datePickerListener = new DatePickerDialog.OnDateSetListener() {
// when dialog box is closed, below method will be called.
public void onDateSet(DatePicker view, int selectedYear,
int selectedMonth, int selectedDay) {
final Calendar cf = Calendar.getInstance();
year = cf.get(Calendar.YEAR);
month = cf.get(Calendar.MONTH);
day = cf.get(Calendar.DAY_OF_MONTH);
// set selected date into textview
shipdate.setText(new StringBuilder().append(month + 1)
.append("-").append(day).append("-").append(year)
.append(" "));
}
};
In Android DatePicker, in some OS it shows Month as "Jan, Feb, Mar...Dec", on other it shows as 1,2,3..12
Is there a way to make it consistent througthout so that it should display 1,2,3.. 12 always as month?
Reason for displaying 1,2,3..12 instead of string is the localization support for various kind of languages.
Also is it advisable to do so?
Thanks.
<?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/btnChangeDate"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Change Date" />
<TextView
android:id="#+id/lblDate"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Current Date (April-10-2012): "
android:textAppearance="?android:attr/textAppearanceLarge" />
<TextView
android:id="#+id/tvDate"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text=""
android:textAppearance="?android:attr/textAppearanceLarge" />
<DatePicker
android:id="#+id/dpResult"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
</LinearLayout>
Date picker class
import java.util.Calendar;
import java.util.Locale;
import com.datepicker.R.string;
import android.app.Activity;
import android.app.DatePickerDialog;
import android.app.Dialog;
import android.os.Bundle;
import android.text.format.DateFormat;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.TextView;
public class DatepickerActivity extends Activity {
private TextView tvDisplayDate;
private DatePicker dpResult;
private Button btnChangeDate;
private int year;
private int month;
private int day;
private String str;
public static long UTC (int year, int month, int day, int hour, int minute, int second) {
return 1;
}
static final int DATE_DIALOG_ID = 999;
//private static final int August =4;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
setCurrentDateOnView();
addListenerOnButton();
}
// display current date
public void setCurrentDateOnView() {
tvDisplayDate = (TextView) findViewById(R.id.tvDate);
dpResult = (DatePicker) findViewById(R.id.dpResult);
final Calendar c = Calendar.getInstance();
year = c.get(Calendar.YEAR);
month = c.get(Calendar. MONTH);
day = c.get(Calendar.DAY_OF_MONTH);
// str=c.getDisplayName(c.MONTH, 2, Locale.US);
// set current date into textview
tvDisplayDate.setText(new StringBuilder()
// Month is 0 based, just add 1
.append(month + 1).append("-").append(day).append("-")
.append(year).append(" "));
// set current date into datepicker
dpResult.init(year, month, day, null);
}
public void addListenerOnButton() {
btnChangeDate = (Button) findViewById(R.id.btnChangeDate);
btnChangeDate.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
showDialog(DATE_DIALOG_ID);
}
});
}
#Override
protected Dialog onCreateDialog(int id) {
switch (id) {
case DATE_DIALOG_ID:
// set date picker as current date
return new DatePickerDialog(this, datePickerListener,year, month,day);
}
return null;
}
private DatePickerDialog.OnDateSetListener datePickerListener = new DatePickerDialog.OnDateSetListener() {
// when dialog box is closed, below method will be called.
public void onDateSet(DatePicker view, int selectedYear,int selectedMonth, int selectedDay) {
year = selectedYear;
month = selectedMonth;
day = selectedDay;
// set selected date into textview
tvDisplayDate.setText(new StringBuilder().append(str + 1)
.append("-").append(day).append("-").append(year)
.append(" "));
// set selected date into datepicker also
dpResult.init(year, month, day, null);
}
};
}