Saturday 1 June 2013

Android Pickers(Date and Time Pickers)

In Android, you can use “android.widget.DatePicker” class to render a date picker component to select day, month and year in a pre-defined user interface and you can use “android.widget.TimePicker” class to render a time picker component to select hour and minute in a pre-defined user interface.

Android provides controls for the user to pick a time or pick a date as ready-to-use dialogs. Each picker provides controls for selecting each part of the time (hour, minute, AM/PM) or date (month, day, year). Using these pickers helps ensure that your users can pick a time or date that is valid, formatted correctly, and adjusted to the user's locale.

Google recommend that you use DialogFragment to host each time or date picker. The DialogFragment manages the dialog lifecycle for you and allows you to display the pickers in different layout configurations, such as in a basic dialog on handsets or as an embedded part of the layout on large screens.

Although DialogFragment was first added to the platform in Android 3.0 (API level 11), if your app supports versions of Android older than 3.0—even as low as Android 1.6—you can use the DialogFragment class that's available in the support library for backward compatibility.


Creating a Date Picker

To display a DatePickerDialog using DialogFragment, you need to define a fragment class that extends DialogFragment and return a DatePickerDialog from the fragment's onCreateDialog() method.

Note: If your app supports versions of Android older than 3.0, be sure you've set up your Android project with the support library as described in Setting Up a Project to Use a Library.

Extending DialogFragment for a date picker

To define a DialogFragment for a DatePickerDialog, you must:

Here's an example:

package com.learnsimply.datetimepickerexample;

import java.util.Calendar;
import android.app.DatePickerDialog;
import android.app.Dialog;
import android.os.Bundle;
import android.support.v4.app.DialogFragment;
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
}
}


Now all you need is an event that adds an instance of this fragment to your activity.

Showing the date picker

Once you've defined a DialogFragment like the one shown above, you can display the date picker by creating an instance of the DialogFragment and calling show().
For example, here's a button that, when clicked, calls a method to show the dialog:


<Button
android:id="@+id/btnChangeDate"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Change Date"
android:onClick="showDatePickerDialog" />

When the user clicks this button, the system calls the following method:


public void showDatePickerDialog(View v) {
DialogFragment newFragment = new DatePickerFragment();
newFragment.show(getSupportFragmentManager(), "datePicker");

  }

Creating a Time Picker

To display a TimePickerDialog using DialogFragment, you need to define a fragment class that extends DialogFragment and return a TimePickerDialog from the fragment's onCreateDialog() method.

Note: If your app supports versions of Android older than 3.0, be sure you've set up your Android project with the support library as described in Setting Up a Project to Use a Library.

Extending DialogFragment for a time picker

To define a DialogFragment for a TimePickerDialog, you must:
Here's an example:



package com.learnsimply.datetimepickerexample;

import java.util.Calendar;
import android.app.Dialog;
import android.app.TimePickerDialog;
import android.os.Bundle;
import android.support.v4.app.DialogFragment;
import android.text.format.DateFormat;
import android.widget.TextView;
import android.widget.TimePicker;

public class TimePickerFragment extends DialogFragment implements TimePickerDialog.OnTimeSetListener{
TextView txtTime;
public TimePickerFragment(TextView txtTime) {
super();
this.txtTime = txtTime;
}

@Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
// Use the current time as the default values for the picker
final Calendar c = Calendar.getInstance();
int hour = c.get(Calendar.HOUR_OF_DAY);
int minute = c.get(Calendar.MINUTE);

// Create a new instance of TimePickerDialog and return it
return new TimePickerDialog(getActivity(), this, hour, minute,
DateFormat.is24HourFormat(getActivity()));
}

public void onTimeSet(TimePicker view, int hourOfDay, int minute) {
// Do something with the time chosen by the user
}
}

Now all you need is an event that adds an instance of this fragment to your activity.

Showing the time picker

Once you've defined a DialogFragment like the one shown above, you can display the time picker by creating an instance of the DialogFragment and calling show().
For example, here's a button that, when clicked, calls a method to show the dialog:


<Button
android:id="@+id/btnChangeTime"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Change Time"
android:onClick="showTimePickerDialog" />


When the user clicks this button, the system calls the following method:

public void showTimePickerDialog(View v) {
DialogFragment newFragment = new TimePickerFragment(txtDisplayTime);
newFragment.show(getSupportFragmentManager(), "timePicker");
}


Run the application





Note: In this sample i use android.support.v4 and FragmentActivity  because DialogFragment was first added to the platform in Android 3.0 (API level 11), if your app supports versions of Android older than 3.0—even as low as Android 1.6—you can use the DialogFragment class that's available in the support library for backward compatibility.

Download Source Code DateTimePicker.zip

Friday 31 May 2013

Android Spinner

In Android, you can use “android.widget.Spinner” class to render a dropdown box selection list.

Spinners provide a quick way to select one value from a set. In the default state, a spinner shows its currently selected value. Touching the spinner displays a dropdown menu with all other available values, from which the user can select a new one.

You can add a spinner to your layout with the Spinner object. You should usually do so in your XML layout with a <Spinner> element.


<Spinner
android:id="@+id/spinner"
android:layout_width="fill_parent"
android:layout_height="wrap_content" />

Here i implements OnItemSelectedListener geting the Spinner selected item. I also set Spinner selected item to a text view (code: selection.setText(items[position]);

1.Spinner

<?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: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="true" />

</LinearLayout>

2.Code

package com.learnsimply.spinnerexample;

import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.ArrayAdapter;
import android.widget.Spinner;
import android.widget.TextView;

public class MainActivity extends Activity implements OnItemSelectedListener{

TextView selection;
Spinner spin;
String[] items = { "India", "USA", "England", "australia", "japan",
"china", "korea" };

/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);

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);

spin.setAdapter(aa);
}

@Override
public void onItemSelected(AdapterView<?> parent, View v, int position,
long id) {
// TODO Auto-generated method stub
selection.setText(items[position]);

}

@Override
public void onNothingSelected(AdapterView<?> arg0) {
// TODO Auto-generated method stub
selection.setText("");

}
}

Run the code



Download Source Code SpinnerExample.zip

Android Toggle Buttons

A toggle button allows the user to change a setting between two states.

You can add a basic toggle button to your layout with the ToggleButton object. Android 4.0 (API level 14) introduces another kind of toggle button called a switch that provides a slider control, which you can add with a Switch object.

The ToggleButton and Switch controls are subclasses of CompoundButton and function in the same manner, so you can implement their behavior the same way.

Toggle Button Click Event

When the user selects a ToggleButton and Switch, the object receives an on-click event.
To define the click event handler, add the android:onClick attribute to the <ToggleButton> or <Switch>element in your XML layout. The value for this attribute must be the name of the method you want to call in response to a click event. The Activity hosting the layout must then implement the corresponding method.

Within the Activity that hosts this layout, the following method handles the click event:

<ToggleButton
android:id="@+id/togglebutton"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:onClick="onToggleClicked"
android:textOff="Sound off"
android:textOn="Sound on" />

Within the Activity that hosts this layout, the following method handles the click event:


public void onToggleClicked(View view) {
// Is the toggle on?
boolean on = ((ToggleButton) view).isChecked();
if (on) {
// Enable Sound
} else {
// Disable Sound
}

}

The method you declare in the android:onClick attribute must have a signature exactly as shown above. Specifically, the method must:


In this tutorial, we show you how to use XML to create two toggle buttons and a normal button, when user click on the normal button, it will display the current state of both toggle buttons.

2. ToggleButton

<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"
tools:context=".MainActivity"
android:orientation="vertical" >

<ToggleButton
android:id="@+id/toggleButton1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="ToggleButton" />

<ToggleButton
android:id="@+id/toggleButton2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="ToggleButton" />

<Button
android:id="@+id/btnDisplay"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Display" />

</LinearLayout>

3. Code 

package com.learnsimply.toggelbuttonexample;

import android.os.Bundle;
import android.app.Activity;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.Toast;
import android.widget.ToggleButton;

public class MainActivity extends Activity {

private ToggleButton toggleButton1, toggleButton2;
private Button btnDisplay;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
InitializeButtonClick();
}


public void InitializeButtonClick() {
toggleButton1 = (ToggleButton) findViewById(R.id.toggleButton1);
toggleButton2 = (ToggleButton) findViewById(R.id.toggleButton2);
btnDisplay = (Button) findViewById(R.id.btnDisplay);
btnDisplay.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
StringBuffer result = new StringBuffer();
result.append("toggleButton1 : ").append(toggleButton1.getText());
result.append("\ntoggleButton2 : ").append(toggleButton2.getText());
Toast.makeText(MainActivity.this, result.toString(),
Toast.LENGTH_SHORT).show();
}
});
}
}

Run the application





Download Source Code ToggelButtonExample.zip