Form Stuff
This tutorial introduces a variety of widgets that are useful when creating forms, such as image buttons, text fields, checkboxes and radio buttons.
- Start a new project named HelloFormStuff.
- Your
res/layout/main.xml
file should already have a basicLinearLayout
:<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:orientation="vertical" android:layout_width="fill_parent" android:layout_height="fill_parent" > </LinearLayout>
For each widget you want to add, just put the respective View inside thisLinearLayout
.
Each section below also assumes that your
HelloFormStuff
Activity has the following default implementation of the onCreate()
method:public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); }
Now select which kind of form widget you'd like to create:
Custom Button
In this section, you will create a button with a custom image instead of text, using the
Button
widget and an XML file that defines three different images to use for the different button states. When the button is pressed, a short message will be displayed.- Copy the images on the right into the
res/drawable/
directory of your project. These will be used for the different button states. - Create a new file in the
res/drawable/
directory namedandroid_button.xml
. Insert the following XML:<?xml version="1.0" encoding="utf-8"?> <selector xmlns:android="http://schemas.android.com/apk/res/android"> <item android:drawable="@drawable/android_pressed" android:state_pressed="true" /> <item android:drawable="@drawable/android_focused" android:state_focused="true" /> <item android:drawable="@drawable/android_normal" /> </selector>
This defines a single drawable resource, which will change its image based on the current state of the button. The first<item>
definesandroid_pressed.png
as the image when the button is pressed (it's been activated); the second<item>
definesandroid_focused.png
as the image when the button is focused (when the button is highlighted using the trackball or directional pad); and the third<item>
definesandroid_normal.png
as the image for the normal state (when neither pressed nor focused). This XML file now represents a single drawable resource and when referenced by aButton
for its background, the image displayed will change based on these three states.Note: The order of the<item>
elements is important. When this drawable is referenced, the<item>
s are traversed in-order to determine which one is appropriate for the current button state. Because the "normal" image is last, it is only applied when the conditionsandroid:state_pressed
andandroid:state_focused
have both evaluated false. - Open the
res/layout/main.xml
file and add theButton
element:<Button android:id="@+id/button" android:layout_width="wrap_content" android:layout_height="wrap_content" android:padding="10dp" android:background="@drawable/android_button" />
Theandroid:background
attribute specifies the drawable resource to use for the button background (which, when saved atres/drawable/android.xml
, is referenced as@drawable/android
). This replaces the normal background image used for buttons throughout the system. In order for the drawable to change its image based on the button state, the image must be applied to the background. - To make the button do something when pressed, add the following code at the end of the
onCreate()
method:final Button button = (Button) findViewById(R.id.button); button.setOnClickListener(new OnClickListener() { public void onClick(View v) { // Perform action on clicks Toast.makeText(HelloFormStuff.this, "Beep Bop", Toast.LENGTH_SHORT).show(); } });
This captures theButton
from the layout, then adds anView.OnClickListener
. TheView.OnClickListener
must implement theonClick(View)
callback method, which defines the action to be made when the button is clicked. In this example, aToast
message will be displayed. - Now run the application.
Edit Text
In this section, you will create a text field for user input, using the
EditText
widget. Once text has been entered into the field, the "Enter" key will display the text in a toast message.- Open the
res/layout/main.xml
file and add theEditText
element (inside theLinearLayout
):<EditText android:id="@+id/edittext" android:layout_width="fill_parent" android:layout_height="wrap_content"/>
- To do something with the text that the user types, add the following code to the end of the
onCreate()
method:final EditText edittext = (EditText) findViewById(R.id.edittext); edittext.setOnKeyListener(new OnKeyListener() { public boolean onKey(View v, int keyCode, KeyEvent event) { // If the event is a key-down event on the "enter" button if ((event.getAction() == KeyEvent.ACTION_DOWN) && (keyCode == KeyEvent.KEYCODE_ENTER)) { // Perform action on key press Toast.makeText(HelloFormStuff.this, edittext.getText(), Toast.LENGTH_SHORT).show(); return true; } return false; } });
This captures theEditText
element from the layout and adds anView.OnKeyListener
. TheView.OnKeyListener
must implement theonKey(View, int, KeyEvent)
method, which defines the action to be made when a key is pressed while the widget has focus. In this case, the method is defined to listen for the Enter key (when pressed down), then pop up aToast
message with the text that has been entered. TheonKey(View, int, KeyEvent)
method should always returntrue
if the event has been handled, so that the event doesn't bubble-up (which would result in a carriage return in the text field). - Run the application.
Checkbox
In this section, you will create a checkbox for selecting items, using the
CheckBox
widget. When the checkbox is pressed, a toast message will indicate the current state of the checkbox.- Open the
res/layout/main.xml
file and add theCheckBox
element (inside theLinearLayout
):<CheckBox android:id="@+id/checkbox" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="check it out" />
- To do something when the state is changed, add the following code to the end of the
onCreate()
method:final CheckBox checkbox = (CheckBox) findViewById(R.id.checkbox); checkbox.setOnClickListener(new OnClickListener() { public void onClick(View v) { // Perform action on clicks, depending on whether it's now checked if (((CheckBox) v).isChecked()) { Toast.makeText(HelloFormStuff.this, "Selected", Toast.LENGTH_SHORT).show(); } else { Toast.makeText(HelloFormStuff.this, "Not selected", Toast.LENGTH_SHORT).show(); } } });
This captures theCheckBox
element from the layout, then adds anView.OnClickListener
. TheView.OnClickListener
must implement theonClick(View)
callback method, which defines the action to be made when the checkbox is clicked. When clicked,isChecked()
is called to check the new state of the check box. If it has been checked, then aToast
displays the message "Selected", otherwise it displays "Not selected". Note that theView
object that is passed in theonClick(View)
callback must be cast to aCheckBox
because theisChecked()
method is not defined by the parentView
class. TheCheckBox
handles its own state changes, so you only need to query the current state. - Run it.
Tip: If you need to change the state yourself (such as when loading a saved
CheckBoxPreference
), use the setChecked(boolean)
or toggle()
method.Radio Buttons
In this section, you will create two mutually-exclusive radio buttons (enabling one disables the other), using the
RadioGroup
and RadioButton
widgets. When either radio button is pressed, a toast message will be displayed.- Open the
res/layout/main.xml
file and add twoRadioButton
s, nested in aRadioGroup
(inside theLinearLayout
):<RadioGroup android:layout_width="fill_parent" android:layout_height="wrap_content" android:orientation="vertical"> <RadioButton android:id="@+id/radio_red" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Red" /> <RadioButton android:id="@+id/radio_blue" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Blue" /> </RadioGroup>
It's important that theRadioButton
s are grouped together by theRadioGroup
element so that no more than one can be selected at a time. This logic is automatically handled by the Android system. When oneRadioButton
within a group is selected, all others are automatically deselected. - To do something when each
RadioButton
is selected, you need anView.OnClickListener
. In this case, you want the listener to be re-usable, so add the following code to create a new member in theHelloFormStuff
Activity:private OnClickListener radio_listener = new OnClickListener() { public void onClick(View v) { // Perform action on clicks RadioButton rb = (RadioButton) v; Toast.makeText(HelloFormStuff.this, rb.getText(), Toast.LENGTH_SHORT).show(); } };
First, theView
that is passed to theonClick(View)
method is cast into a RadioButton. Then aToast
message displays the selected radio button's text. - Now, at the bottom of the
onCreate()
method, add the following:final RadioButton radio_red = (RadioButton) findViewById(R.id.radio_red); final RadioButton radio_blue = (RadioButton) findViewById(R.id.radio_blue); radio_red.setOnClickListener(radio_listener); radio_blue.setOnClickListener(radio_listener);
This captures each of theRadioButton
s from the layout and adds the newly-createdView.OnClickListener
to each. - Run the application.
Tip: If you need to change the state yourself (such as when loading a saved
CheckBoxPreference
), use the setChecked(boolean)
or toggle()
method.Toggle Button
In this section, you'll create a button used specifically for toggling between two states, using the
ToggleButton
widget. This widget is an excellent alternative to radio buttons if you have two simple states that are mutually exclusive ("on" and "off", for example).- Open the
res/layout/main.xml
file and add theToggleButton
element (inside theLinearLayout
):<ToggleButton android:id="@+id/togglebutton" android:layout_width="wrap_content" android:layout_height="wrap_content" android:textOn="Vibrate on" android:textOff="Vibrate off"/>
The attributesandroid:textOn
andandroid:textOff
specify the text for the button when the button has been toggled on or off. The default values are "ON" and "OFF". - To do something when the state is changed, add the following code to the end of the
onCreate()
method:final ToggleButton togglebutton = (ToggleButton) findViewById(R.id.togglebutton); togglebutton.setOnClickListener(new OnClickListener() { public void onClick(View v) { // Perform action on clicks if (togglebutton.isChecked()) { Toast.makeText(HelloFormStuff.this, "Checked", Toast.LENGTH_SHORT).show(); } else { Toast.makeText(HelloFormStuff.this, "Not checked", Toast.LENGTH_SHORT).show(); } } });
This captures theToggleButton
element from the layout, then adds anView.OnClickListener
. TheView.OnClickListener
must implement theonClick(View)
callback method, which defines the action to perform when the button is clicked. In this example, the callback method checks the new state of the button, then shows aToast
message that indicates the current state.Notice that theToggleButton
handles its own state change between checked and unchecked, so you just ask which it is. - Run the application.
Tip: If you need to change the state yourself (such as when loading a saved
CheckBoxPreference
), use the setChecked(boolean)
or toggle()
method.Rating Bar
In this section, you'll create a widget that allows the user to provide a rating, with the
RatingBar
widget.- Open the
res/layout/main.xml
file and add theRatingBar
element (inside theLinearLayout
):<RatingBar android:id="@+id/ratingbar" android:layout_width="wrap_content" android:layout_height="wrap_content" android:numStars="5" android:stepSize="1.0"/>
Theandroid:numStars
attribute defines how many stars to display for the rating bar. Theandroid:stepSize
attribute defines the granularity for each star (for example, a value of0.5
would allow half-star ratings). - To do something when a new rating has been set, add the following code to the end of the
onCreate()
method:final RatingBar ratingbar = (RatingBar) findViewById(R.id.ratingbar); ratingbar.setOnRatingBarChangeListener(new OnRatingBarChangeListener() { public void onRatingChanged(RatingBar ratingBar, float rating, boolean fromUser) { Toast.makeText(HelloFormStuff.this, "New Rating: " + rating, Toast.LENGTH_SHORT).show(); } });
This captures theRatingBar
widget from the layout withfindViewById(int)
and then sets anRatingBar.OnRatingBarChangeListener
. TheonRatingChanged()
callback method then defines the action to perform when the user sets a rating. In this case, a simpleToast
message displays the new rating. - Run the application.
If you've added all the form widgets above, your application should look like this:
Final Out Put
hey nice tutorial .. i want to build an app that takes 3 inputs from user via text fields namely name , address and phone no and sends those details via sms to a particular contact from the database..the contacts will be present inside the database in the phone (mysql lite database)
ReplyDeleteSo basically when i click the button to send sms it should show all the contacts that are present in my database after which i can select and send sms
how to do this ? can u post a code for the same?
Thanks
Hey the tutorial is good ..
ReplyDeleteI wanted to know whether the following is possible or not ?
Create 3 text fields ..values of those text fields must come from database on android phone (mysql lite database) in the form of a drop down list..on sumbitting it should send sms to any particular contact ( again contacts present in database must be displayed and user should select )
how can we do this ? any ideas?