Saturday, February 15, 2014

Android DatePicker.

activity_main.xml


<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:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context=".MainActivity" >

    <Button
        android:id="@+id/btnChangeDate"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="@string/cd" />

    <DatePicker
        android:id="@+id/dpResult"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentBottom="true"
        android:layout_alignParentLeft="true"
        android:layout_alignParentRight="true"
        android:layout_marginBottom="38dp" />

    <TextView
        android:id="@+id/textView1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_above="@+id/dpResult"
        android:layout_alignLeft="@+id/dpResult"
        android:layout_marginBottom="20dp"
        android:layout_marginLeft="20dp"
        android:text="@string/cd1" />

</RelativeLayout>


MainActivity.java


package com.mahi.datepicker;

import android.os.Bundle;
import android.app.Activity;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.TextView;

public class MainActivity extends Activity {
DatePicker dp;
    Button b;
    TextView textview1;

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
textview1=(TextView)findViewById(R.id.textView1);
        dp=(DatePicker)findViewById(R.id.dpResult);
        b=(Button)findViewById(R.id.btnChangeDate);
        
        textview1.setText(getCurrentDate());
        
        b.setOnClickListener(new OnClickListener(){
            @Override  
            public void onClick(View view) {
                textview1.setText(getCurrentDate());
            }
              
        });
}
public String getCurrentDate(){
        StringBuilder builder=new StringBuilder();
        builder.append("Current Date: ");
        builder.append((dp.getMonth() + 1)+"/");//month is 0 based
        builder.append(dp.getDayOfMonth()+"/");
        builder.append(dp.getYear());
        return builder.toString();
    }

@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
}


Output:



No comments:

Post a Comment