Please have a look at the following code
activity_main.xml
<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"
>
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/btnText"
/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/heading"
/>
<TextView
android:id="@+id/text"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
/>
<DatePicker
android:id="@+id/date"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
/>
</LinearLayout>
MainActivity.java
package com.example.datepicker;
import android.os.Bundle;
import android.app.Activity;
import android.app.DatePickerDialog.OnDateSetListener;
import android.view.Menu;
import android.widget.DatePicker;
import android.widget.Toast;
public class MainActivity extends Activity {
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
DatePicker dp = (DatePicker)findViewById(R.id.date);
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.activity_main, menu);
return true;
}
private class DatePickerMe implements OnDateSetListener
{
public void onDateSet(DatePicker arg0, int arg1, int arg2, int arg3)
{
Toast.makeText(MainActivity.this, "Click", Toast.LENGTH_LONG);
}
}
}
Here, I want to display the “Toast” message whenever the date is changed. I have attempted it under “DatePickerMe” inner class. But however, I don’t know how to register this “OnDateSetListener” to date picker (I assumed onDateSetListener is the correct interface). Please help me to display the text, whenever the date is changed.
Thanks
I noticed a few things:
DatePicker#init()to set your OnDateChangedListener.show()on your Toast, otherwise it will never display.Try this: