Hi developers, here the example for simple calendar control in android.
CalendarActivity .java
public class CalendarActivity extends Activity
{
private EditText Calctrl;
static final int DATE_DIALOG_ID = 0;
final Calendar c = Calendar.getInstance();
private int mYear, mMonth, mDay;
private String sdate;
private String[] arrayMonth = { "Jan", "Feb", "Mar", "Apr", "May", "Jun",
"Jul", "Aug", "Sep", "Oct", "Nov", "Dec" };
@Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
Calctrl = (EditText) findViewById(R.id.datepicker);
mYear = c.get(Calendar.YEAR);
mMonth = c.get(Calendar.MONTH);
mDay = c.get(Calendar.DAY_OF_MONTH);
sdate = currentDate(mYear, mMonth, mDay);
Calctrl.setText(sdate);
Calctrl.setOnTouchListener(new OnTouchListener()
{
@Override
public boolean onTouch(View v, MotionEvent event)
{
showDialog(DATE_DIALOG_ID);
return true;
}
});
}
@Override
protected Dialog onCreateDialog(int id)
{
switch (id)
{
case DATE_DIALOG_ID:
return new DatePickerDialog(this, mDateSetListener, mYear, mMonth,mDay);
}
return null;
}
@Override
protected void onPrepareDialog(int id, Dialog dialog)
{
switch (id)
{
case DATE_DIALOG_ID:
((DatePickerDialog) dialog).updateDate(mYear, mMonth, mDay);
break;
}
}
private DatePickerDialog.OnDateSetListener mDateSetListener = new DatePickerDialog.OnDateSetListener()
{
public void onDateSet(DatePicker view, int year, int monthOfYear,int dayOfMonth)
{
mYear = year;
mMonth = monthOfYear;
mDay = dayOfMonth;
String sdate = currentDate(mYear, mMonth, mDay);
Calctrl.setText(sdate);
}
};
private static String LPad(String schar, String spad, int len)
{
String sret = schar;
for (int i = sret.length(); i < len; i++)
{
sret = spad + sret;
}
return new String(sret);
}
private String currentDate(int year, int month, int day)
{
String sdate = arrayMonth[month] + " " + LPad(day + "", "0", 2) + ", "+ year;
return sdate;
}
}
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:background="@drawable/app_background"
android:orientation="vertical" >
<EditText
android:id="@+id/datepicker"
android:layout_width="150dp"
android:layout_height="wrap_content"
android:editable="false"
android:inputType="none" />
</LinearLayout>
i want to click particular date and open new activity
ReplyDelete