Showing posts with label Android UI Controls. Show all posts
Showing posts with label Android UI Controls. Show all posts

Friday, 16 August 2013

Android UI Control tutorials by JAVATYRO

// siddhu vydyabhushana // 5 comments
top-10 android ui control tutorials
http://javatyro.blogspot.in/2013/07/android-relativelayout-example.html

http://javatyro.blogspot.in/2013/07/android-listview-example.html

http://javatyro.blogspot.in/2013/07/android-password-field-example.html

http://javatyro.blogspot.in/2013/07/android-checkbox-example.html

http://javatyro.blogspot.in/2013/07/android-radio-buttons-example.html

http://javatyro.blogspot.in/2013/07/android-spinner-drop-down-list-example.html

http://javatyro.blogspot.in/2013/07/android-toast-example.html

http://javatyro.blogspot.in/2013/07/android-date-picker-example.html

http://javatyro.blogspot.in/2013/07/android-imageview-example.html

http://javatyro.blogspot.in/2013/07/android-prompt-user-input-dialog-example.html

http://javatyro.blogspot.in/2013/07/android-progress-bar-example.html

http://javatyro.blogspot.in/2013/07/android-custom-dialog-example.html

http://javatyro.blogspot.in/2013/07/android-alert-dialog-example.html
Read More

Thursday, 15 August 2013

Android bEGINNER : Basic text controls

// siddhu vydyabhushana // 8 comments
In this tutorial, you’ll learn how to create basic Android text controls. Then you’ll learn how to configure, style, and manipulate the controls in a variety of ways.

This tutorial shows you the steps to create a number of different TextView controls in your Android application. First, you learn how to add basic text controls to your layout files and what some of their most useful attributes are. Next, you learn how to set the text control’s contents in two different ways. Finally, we discuss some of the other features available to TextView control in Android.
The Android SDK includes a simple static text control for use within your layouts: TextView (android.widget.TextView). A good example of TextView control usage would be to display textual labels for other controls, like “Enter a Date:”, “Enter a Name:” or “Enter a Password:”.
Here is an example of a screen with many different TextView controls displayed on it.
Android screen with numerous TextView controls

Step 1: Create an Android Application

Begin by creating an Android project. Implement your Android application as normal. Once you have a project set up and the application running, decide under what screen you want to add text controls to. Perhaps you’ve simply created a new Android project with its default Activity and layout (main.xml). This will work for this exercise. Once you have gotten your Android project set up, you are ready to proceed with this tutorial.

Step 2: Adding a TextView Control to a Layout

TextView controls are usually included as part of your Activity’s layout resource file. For example, to add a TextView control to the main.xml layout resource associated with your application, you must edit the layout file. You can do this within Eclipse using the Layout Resource designer, or by editing the XML directly. Controls can also be created programmatically and added to your screen at runtime. Simply create a Textview control (android.widget.TextView) and add it to your layout within your Activity.
To add a TextView control to a layout resource file, open the /res/layout/main.xml layout file that is part of your Android project. Click on the LinearLayout (or parent layout control) that you wish to add the TextView control to. In Eclipse from within the graphical Layout Resource designer, you can select the TextView control and drag it into the parent layout.
To configure how the TextView control looks and behaves, adjust the control’s attributes by selecting the control (either in the Outline tab or the Preview window) and changing its attributes, as shown the Properties Tab. You can also edit the XML directly.
Specific attributes of TextView controls you will want to be aware of:
  • Give the TextView control a unique name using the id property.
  • Set the text displayed within the TextView control using the text property; programmatically set with the setText() method.
  • Set the layout height and layout width properties of the control as appropriate.
  • Set any other attributes you desire to adjust the control’s appearance. For example, adjust the text size, color, font or other style settings.
Let’s discuss some of the most common attributes for TextView controls.

Step 3: Aligning Text within a TextView Control

By default, text contents of a TextView control are left-aligned. However, you can position the text using the gravity attribute. This setting positions your text relative to the control’s overall width and height and only really makes sense to use if there is whitespace within the TextView control because you’ve set it’s layout_height and/or layout_width to something other than wrap_content. In XML, this property would appear within your TextView control as:
android:gravity="center"
You can see an example of a center-aligned TextView control in the figure above, referred to as “Centered Text”. This TextView control has a layout_width of match_parent and a layout_height of wrap_content.
If you’re working with TextView control’s in your Java code, you can also set the alignment of your TextView control programmatically using the setGravity() method of the TextView class.

Step 4: Controlling the Background of a TextView Control

By default, the background of a TextView control is transparent. That is, whatever is behind the control is shown. However, you can set the background of a control explicitly, to a color resource, or a drawable (picture). In XML, this property would appear within your TextView control as:
1
android:background="#0000ff"
You can see an example of a TextView control with a blue background in the figure above. This TextView control has a layout_width of match_parent and a layout_height of wrap_content. Note that the entire control has the background, not just the area with the text contents.
If you’re working with TextView control’s in your Java code, you can also set the alignment of your TextView control programmatically using the setBackgroundResource() method of the View class.

Step 5: Automatically Linking TextView Control Contents

By default, any text contents within a TextView control is displayed as plain text. However, by setting one simple attribute called autoLink, all you can enable automatic detection of web, email, phone and address information within the text. In XML, this property would appear within your TextView control as:
1
android:autoLink="all"
You can see an example of a TextView control with automatic links in the figure above. This TextView control has no special handling link processing; its contents are just a string. The Android operating system detects the phone number, which, when clicked, launches the Phone application. Similarly, the email launches the user’s preferred email app. The URL launches the Browser application. If you were to include a fully resolvable address, it would be linked with the Maps application.
If you’re working with TextView control’s in your Java code, you can also set the autoLink feature of your TextView control programmatically using the setAutoLinkMask() method of the TextView class.

Step 6: Working with Multi-Line TextView Controls

By default, text contents of a TextView control will wrap and continue on multiple lines unless you specify otherwise. You can customize this behavior in a number of ways:
  • You can use the android:lines attribute to set the TextView control to a specific number of lines.
  • You can use the android:minLines and android:maxLines attribute to set the TextView control to a never grow smaller or larger than specific number of lines.
  • You can use the android:singleLine attribute to avoid wrapping onto multiple lines, but instead provide a one line alterative view of the text.
  • You can use the android:lineSpacingExtra attribute to specify the distance of whitespace between each line (e.g. double spaced for readability).
You can see examples of multi-line and line-spaced TextView controls in the figure above.
If you’re working with TextView control’s in your Java code, you can also modify these settings programmatically using the appropriate methods of the TextView class (see the TextView class information with the Android SDK documentation for details).

Step 7: Customizing the Text Color of a TextView Control

You can control the color of the text within the TextView control by using the textColor attribute. This attribute can be set to a color resource, or a specific color by hex value. In XML, this property would appear within your TextView control as:
1
android:textColor="#ff0000"
You can see an example of a red TextView control in the figure above. If you’re working with TextView control’s in your Java code, you can also set the color attribute of your TextView control programmatically using the setTextColor() method of the TextView class.
You can also create a rather subtle kind of glow effect on your TextView control using the shadowColor, shadowDx, shadowDy, and shadowRadius attributes, as shown in the bottom TextView control of the figure. These attributes are programmatically equivalent to the setShadowLayer() method of the TextView class.

Step 8: Customizing the Styling and Font Family of a TextView Control

You can control the style of the text (bold, italic) and font family (sans, serif, monospace) within the TextView control by using the textStyle and typeface attributes. In XML, these properties would appear within your TextView control as:
1
2
android:textStyle="bold"
android:typeface="monospace"
You can see examples of bold and monospace TextView controls in the figure above. If you’re working with TextView control’s in your Java code, you can also set the both attributes of your TextView control programmatically using the setTypeface() method of the TextView class

Conclusion

TextView controls are commonly used in Android application user interfaces to display text contents in different ways. In this tutorial, you learned how to create Android text controls and customize them in a variety of simple ways. These attributes can be mixed and matched to allow for very flexible text display on the screen.
Read More

Android Beginner : basic buttons design in android

// siddhu vydyabhushana // 5 comments
This quick tip shows you the steps to create a simple Button or ImageButton control in your Android application. First, you learn how to add button controls to your layout files. Next, you learn how to handle button clicks from the user in two different ways. Finally, we discuss some of the other features available to button controls in Android.

Step 1: Create an Android Application

Begin by creating an Android project. Implement your Android application as normal. Once you have a project set up and the application running, decide under what screen you want to add Button controls to. Perhaps you’ve simply created a new Android project with its default Activity and layout (main.xml). This will work for this tutorial. Once you have gotten your Android project set up, you are ready to proceed with this quick tip.
You can follow along with our project: BasicButtons, which is available as an open source project.

Step 2: Working with Button Controls

The Android SDK includes two simple button controls for use within your layouts: Button (android.widget.Button) and ImageButton (android.widget.ImageButton). These controls function in a similar way so we can discuss them pretty much interchangeably. The difference between the controls is mostly visual; the Button control has a text label, whereas the ImageButton uses an image drawable resource instead. A good example of Button usage would be a simple button with a text label “Save”. A good example of ImageButton usage would a set of musically-inspired buttons with the symbols for Play (), Pause () and Stop ( ).
Here is an example of a screen with both a Button control (left) and an ImageButton control (right).
Android screen with two types of button controls
The Android SDK also includes several other lesser-known button-like controls derived from these two basic button types, including CompoundButton, RadioButton, ToggleButton, and ZoomButton. For more information on these controls, see the Android documentation. You can also create custom controls yourself by deriving from the appropriate class and implementing the control’s behavior.

Step 3: Adding a Button Control to a Layout

Button controls are usually included as part of your Activity’s layout resource file. For example, to add a Button control to the main.xml layout resource associated with your application, you must edit the layout file. You can do this within Eclipse using the Layout Resource designer, or by editing the XML directly. Controls such as buttons can also be created programmatically and added to your screen at runtime. Simply create the appropriate control from its class and add it to your layout within your Activity.
To add a Button control to a layout resource file, open the /res/layout/main.xml layout file that is part of your Android project. Click on the LinearLayout (or parent layout control, such as a RelativeLayout or FrameLayout) that you wish to add the Button control to. In Eclipse, you can click on the parent layout within the Outline tab, and then add a new control using the green button with the plus sign. Choose the control you want to add—in this case, a Button control.
Adding a Button control to a Layout Resource in Eclipse
To configure how the Button control looks, adjust the control’s properties by selecting the control (either in the Outline tab or the Preview window) and changing its properties in the Properties Tab. Specific properties you will want to be aware of:
  • Give the Button or ImageButton control a unique name using the id property.
  • Set the text displayed on the Button control using the text property; set the image displayed on the ImageButton control using the src property.
  • Set the layout height and layout width properties of the control to wrap_content.
  • Set any other properties you desire to adjust the control’s appearance. For example, adjust the font of a Button using the Text color, text size, and text style properties.
Here is the content of the layout resource file used to generate the screen shown in the previous section. It contains three controls. The RelativeLayout organizes the controls on the screen,namely the two child controls, a Button and an ImageButton, as shown here:
  1. <?xml version="1.0" encoding="utf-8"?>  
  2. <RelativeLayout  
  3.     xmlns:android="http://schemas.android.com/apk/res/android"  
  4.     android:layout_width="fill_parent"  
  5.     android:layout_height="fill_parent"  
  6.     android:gravity="center">  
  7.     <Button  
  8.         android:id="@+id/Button01"  
  9.         android:layout_width="wrap_content"  
  10.         android:layout_height="wrap_content"  
  11.         android:text="@string/hello"  
  12.         android:minHeight="92dp"  
  13.         android:textSize="22dp"  
  14.         android:onClick="onMyButtonClick"></Button>  
  15.     <ImageButton  
  16.         android:layout_width="wrap_content"  
  17.         android:layout_height="wrap_content"  
  18.         android:src="@drawable/skater"  
  19.         android:id="@+id/ImageButton01"  
  20.         android:layout_toRightOf="@+id/Button01"></ImageButton>  
  21. </RelativeLayout>  

Step 4: Handling Clicks – The Easy Way

For now, if you launch this application, the button controls are displayed, but nothing happens if you click on them. Now it’s time to handle clicks on the controls. There are several ways to do this.
Let’s start with the easy way. Button and ImageButton controls have a property called onClick (shown as “On Click” in the properties pane).. You set the name of the method that will handle the click with this property, and then implement that method within your Activity. For example, you could set the property of your Button control to onMyButtonClick. In XML, this property would appear as:
  1. android:onClick="onMyButtonClick"  
Then, in your Activity class, you need to implement this method. It should be a public void method with a single parameter, a View object. For example, the following button click implementation generates a Toast message on the screen when the Button control is clicked:
  1. public void onMyButtonClick(View view)  
  2. {  
  3.     Toast.makeText(this"Button clicked!", Toast.LENGTH_SHORT).show();  
  4. }  
When you click on the Button control, the onMyButtonClick() method is called, displaying the Toast message on the screen. The details of what your Button control does is up to you. Here’s what the Toast message would look like when you pressed the Button control:
Handling a Button control click with a Toast

Step 5: Handling Clicks – Implementing an OnClickListener

The other way to implement your click handling is to register a new View.OnClickListener with your button control using the setOnClickListener() method. Instead of setting the On Click property of your button control in your layout resource to a method you must implement, you do this programmatically within your Activity. While this might seem like a lot of extra code to write, it’s important to at least understand it, as clicks are not the only event worth handling on certain controls. The programmatic method we are about to show you applies to other events such as long clicks.
To use this method, you must update your Activity class to register for control clicks. This is typically done within the onCreate() method of your Activity. Retrieve the control using the findViewById() method and then use its the setOnClickListener() method to define the behavior of the control when clicked. You will need to implement the onClick() method of the interface yourself. For example, the following code (placed in the onCreate() method of the Activity) registers a click handler for our ImageButton control.
  1. ImageButton myImageButton = (ImageButton) findViewById(R.id.ImageButton01);  
  2. myImageButton.setOnClickListener(new View.OnClickListener() {  
  3.     public void onClick(View v) {  
  4.                     Toast.makeText(BasicButtonActivity.this"ImageButton clicked!", Toast.LENGTH_SHORT).show();  
  5.             }  
  6. });  
Similarly, you can use this technique to implement long click handling using the control’s setOnLongClickListener() method.

Conclusion

Button controls are commonly used in Android application user interfaces. In this quick tip you learned how to create two different types of Android button controls: the Button and the ImageButton. You also learned several ways to implement button click handlers for these types of controls.
Read More

Tuesday, 2 July 2013

Android date picker example

// siddhu vydyabhushana // 16 comments
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.
In this tutorial, we show you how to render date picker component in current page via android.widget.DatePicker, and also in dialog box via android.app.DatePickerDialog. In addition, we also show you how to set a date in date picker component.
P.S This project is developed in Eclipse 3.7, and tested with Android 2.3.3.

1. DatePicker

Open “res/layout/main.xml” file, add date picker, label and button for demonstration.
File : res/layout/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:orientation="vertical" >
 
    <Button
        android:id="@+id/btnChangeDate"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Change Date" />
 
    <TextView
        android:id="@+id/lblDate"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Current Date (M-D-YYYY): "
        android:textAppearance="?android:attr/textAppearanceLarge" />
 
    <TextView
        android:id="@+id/tvDate"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text=""
        android:textAppearance="?android:attr/textAppearanceLarge" />
 
    <DatePicker
        android:id="@+id/dpResult"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content" />
 
</LinearLayout>
P.S The “DatePickerDialog” is declare in code, not XML.

2. Code Code

Read the code’s comment, it should be self-explanatory.
File : MyAndroidAppActivity.java
package com.mkyong.android;
 
import java.util.Calendar;
import android.app.Activity;
import android.app.DatePickerDialog;
import android.app.Dialog;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.TextView;
 
public class MyAndroidAppActivity extends Activity {
 
	private TextView tvDisplayDate;
	private DatePicker dpResult;
	private Button btnChangeDate;
 
	private int year;
	private int month;
	private int day;
 
	static final int DATE_DIALOG_ID = 999;
 
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.main);
 
		setCurrentDateOnView();
		addListenerOnButton();
 
	}
 
	// display current date
	public void setCurrentDateOnView() {
 
		tvDisplayDate = (TextView) findViewById(R.id.tvDate);
		dpResult = (DatePicker) findViewById(R.id.dpResult);
 
		final Calendar c = Calendar.getInstance();
		year = c.get(Calendar.YEAR);
		month = c.get(Calendar.MONTH);
		day = c.get(Calendar.DAY_OF_MONTH);
 
		// set current date into textview
		tvDisplayDate.setText(new StringBuilder()
			// Month is 0 based, just add 1
			.append(month + 1).append("-").append(day).append("-")
			.append(year).append(" "));
 
		// set current date into datepicker
		dpResult.init(year, month, day, null);
 
	}
 
	public void addListenerOnButton() {
 
		btnChangeDate = (Button) findViewById(R.id.btnChangeDate);
 
		btnChangeDate.setOnClickListener(new OnClickListener() {
 
			@Override
			public void onClick(View v) {
 
				showDialog(DATE_DIALOG_ID);
 
			}
 
		});
 
	}
 
	@Override
	protected Dialog onCreateDialog(int id) {
		switch (id) {
		case DATE_DIALOG_ID:
		   // set date picker as current date
		   return new DatePickerDialog(this, datePickerListener, 
                         year, month,day);
		}
		return null;
	}
 
	private DatePickerDialog.OnDateSetListener datePickerListener 
                = new DatePickerDialog.OnDateSetListener() {
 
		// when dialog box is closed, below method will be called.
		public void onDateSet(DatePicker view, int selectedYear,
				int selectedMonth, int selectedDay) {
			year = selectedYear;
			month = selectedMonth;
			day = selectedDay;
 
			// set selected date into textview
			tvDisplayDate.setText(new StringBuilder().append(month + 1)
			   .append("-").append(day).append("-").append(year)
			   .append(" "));
 
			// set selected date into datepicker also
			dpResult.init(year, month, day, null);
 
		}
	};
 
}
P.S The “DatePickerDialog” example above, is referenced from Google Android date picker example, with some minor change.

3. Demo

Run the application.
1. Result, “date picker” and “textview” are set to current date.
android datepicker demo1
2. Click on the “Change Date” button, it will prompt a date picker component in a dialog box via DatePickerDialog.
android datepicker demo2
3. Both “date picker” and “textview” are updated with selected date.
android datepicker demo3

Download Source Code

Download it – Android-DatePicker-Example.zip (16 KB)
Read More

Android ImageView example

// siddhu vydyabhushana // 5 comments
In Android, you can use “android.widget.ImageView” class to display an image file. Image file is easy to use but hard to master, because of the various screen and dpi in Android devices.
Note
Please refer to this official Android’s “Drawable Resource” and “Screen Support” article for better understand of how image works in Android.
In this tutorial, we didn’t go in deep about dpi and various screen issue, we just use ImageView to display a “png” image, when user click on a button, it will change to another “png” image.
P.S This project is developed in Eclipse 3.7, and tested with Android 2.3.3.

1. Add Image to Resources

Put your images into folder “res/drawable-ldpi“, “res/drawable-mdpi” or “res/drawable-hdpi“.
See figure below, no matter which folder you put, Android will find your image automatically. In this case, both “android.png” and “android3d.png” images are used for demonstration.
android image drawable
Note
Again, read official Android’s “Drawable Resource” and “Screen Support” article to understand what is dpi and resources in Android.

2. Add ImageView

Open “res/layout/main.xml” file, just add an ImageView and Button for demonstration. By default, imageView1 will display “android.png”.
File : res/layout/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:orientation="vertical" >
 
    <ImageView
        android:id="@+id/imageView1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:src="@drawable/android" />
 
    <Button
        android:id="@+id/btnChangeImage"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Change Image" />
 
</LinearLayout>

3. Code Code

Simple, when button is clicked, change it to “android3d.png”.
File : MyAndroidAppActivity.java
package com.mkyong.android;
 
import android.app.Activity;
import android.os.Bundle;
import android.widget.Button;
import android.widget.ImageView;
import android.view.View;
import android.view.View.OnClickListener;
 
public class MyAndroidAppActivity extends Activity {
 
	Button button;
	ImageView image;
 
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.main);
 
		addListenerOnButton();
 
	}
 
	public void addListenerOnButton() {
 
		image = (ImageView) findViewById(R.id.imageView1);
 
		button = (Button) findViewById(R.id.btnChangeImage);
		button.setOnClickListener(new OnClickListener() {
 
			@Override
			public void onClick(View arg0) {
				image.setImageResource(R.drawable.android3d);
			}
 
		});
 
	}
 
}

4. Demo

Run the application.
1. Result, “android.png” is displayed.
android imageview demo1
2. Click on the button, image will changed to “android3d.png”.
android imageview demo2

Download Source Code

Download it – Android-ImageView-Example.zip (57 KB)
Read More

Android prompt user input dialog example

// siddhu vydyabhushana // 4 comments
In this tutorial, we will enchance the previous AlertDialog example, to make it able to accept user input, just like a PromptDialog. More specific, this is a custom AlertDialog example.
See following steps :
  1. Create a prompt dialog layout (XML file).
  2. Attach the prompt dialog layout to AlertDialog.Builder.
  3. Attach the AlertDialog.Builder to AlertDialog.
  4. Done.
P.S This project is developed in Eclipse 3.7, and tested with Android 2.3.3.
Note
You may interest to read this custom dialog example.

1 Android Layout Files

Two XML files, one for main screen, one for prompt dialog.
File : res/layout/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:orientation="vertical" >
 
    <Button
        android:id="@+id/buttonPrompt"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Show Prompt Dialog" />
 
    <EditText
        android:id="@+id/editTextResult"
        android:layout_width="match_parent"
        android:layout_height="wrap_content" >
 
    </EditText>
 
</LinearLayout>
File : res/layout/prompts.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/layout_root"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="vertical"
    android:padding="10dp" >
 
    <TextView
        android:id="@+id/textView1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Type Your Message : "
        android:textAppearance="?android:attr/textAppearanceLarge" />
 
    <EditText
        android:id="@+id/editTextDialogUserInput"
        android:layout_width="match_parent"
        android:layout_height="wrap_content" >
 
        <requestFocus />
 
    </EditText>
 
</LinearLayout>

2. Activity

Read the comment and demo in next step, it should be self-explorary.
File : MainActivity.java
package com.mkyong.android;
 
import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
 
public class MainActivity extends Activity {
 
	final Context context = this;
	private Button button;
	private EditText result;
 
	public void onCreate(Bundle savedInstanceState) {
 
		super.onCreate(savedInstanceState);
		setContentView(R.layout.main);
 
		// components from main.xml
		button = (Button) findViewById(R.id.buttonPrompt);
		result = (EditText) findViewById(R.id.editTextResult);
 
		// add button listener
		button.setOnClickListener(new OnClickListener() {
 
			@Override
			public void onClick(View arg0) {
 
				// get prompts.xml view
				LayoutInflater li = LayoutInflater.from(context);
				View promptsView = li.inflate(R.layout.prompts, null);
 
				AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(
						context);
 
				// set prompts.xml to alertdialog builder
				alertDialogBuilder.setView(promptsView);
 
				final EditText userInput = (EditText) promptsView
						.findViewById(R.id.editTextDialogUserInput);
 
				// set dialog message
				alertDialogBuilder
					.setCancelable(false)
					.setPositiveButton("OK",
					  new DialogInterface.OnClickListener() {
					    public void onClick(DialogInterface dialog,int id) {
						// get user input and set it to result
						// edit text
						result.setText(userInput.getText());
					    }
					  })
					.setNegativeButton("Cancel",
					  new DialogInterface.OnClickListener() {
					    public void onClick(DialogInterface dialog,int id) {
						dialog.cancel();
					    }
					  });
 
				// create alert dialog
				AlertDialog alertDialog = alertDialogBuilder.create();
 
				// show it
				alertDialog.show();
 
			}
		});
	}
}

3. Demo

Start it, the “main.xml” layout is display a button and edittext (result).
android prompt user input example
Click on the button, display a prompt dialog “prompts.xml” layout, type message “mkyong“, and click on the “OK” button.
android prompt user input example
User input “mkyong” will pass to the “main.xml” layout, edittext (result), and display it.
android prompt user input example

Download Source Code

Download it – Android-Prompt-Dialog-Example.zip (16 KB)
Read More

Android progress bar example

// siddhu vydyabhushana // 8 comments
In Android, progress bar is useful to tell user that the task is takes longer time to finish.
In this tutorial, we show you how to display a progress bar dialog to tell user that your task is running, and also how to increase the progress bar status until the task is completed.
Note
Refer to this Android ProgressBar JavaDoc for detail explanation.
P.S This project is developed in Eclipse 3.7, and tested with Android 2.3.3.

1. Add a Button

Open “res/layout/main.xml” file, just add normal button for demonstration.
File : res/layout/main.xml
<?xml version="1.0" encoding="utf-8"?>
<?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" >
 
    <Button
        android:id="@+id/btnStartProgress"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Download File" />
 
</LinearLayout>

2. Code Code

The key to use progress bar is using “Thread” to run your time consume task and another “Thread” to update the progress bar status accordingly. Read the code’s comment, it should be self-explanatory.
File : MyAndroidAppActivity.java
package com.mkyong.android;
 
import android.app.Activity;
import android.app.ProgressDialog;
import android.os.Bundle;
import android.os.Handler;
import android.widget.Button;
import android.view.View;
import android.view.View.OnClickListener;
 
public class MyAndroidAppActivity extends Activity {
 
	Button btnStartProgress;
	ProgressDialog progressBar;
	private int progressBarStatus = 0;
	private Handler progressBarHandler = new Handler();
 
	private long fileSize = 0;
 
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.main);
 
		addListenerOnButton();
 
	}
 
	public void addListenerOnButton() {
 
		btnStartProgress = (Button) findViewById(R.id.btnStartProgress);
		btnStartProgress.setOnClickListener(
                 new OnClickListener() {
 
		   @Override
		   public void onClick(View v) {
 
			// prepare for a progress bar dialog
			progressBar = new ProgressDialog(v.getContext());
			progressBar.setCancelable(true);
			progressBar.setMessage("File downloading ...");
			progressBar.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
			progressBar.setProgress(0);
			progressBar.setMax(100);
			progressBar.show();
 
			//reset progress bar status
			progressBarStatus = 0;
 
			//reset filesize
			fileSize = 0;
 
			new Thread(new Runnable() {
			  public void run() {
				while (progressBarStatus < 100) {
 
				  // process some tasks
				  progressBarStatus = doSomeTasks();
 
				  // your computer is too fast, sleep 1 second
				  try {
					Thread.sleep(1000);
				  } catch (InterruptedException e) {
					e.printStackTrace();
				  }
 
				  // Update the progress bar
				  progressBarHandler.post(new Runnable() {
					public void run() {
					  progressBar.setProgress(progressBarStatus);
					}
				  });
				}
 
				// ok, file is downloaded,
				if (progressBarStatus >= 100) {
 
					// sleep 2 seconds, so that you can see the 100%
					try {
						Thread.sleep(2000);
					} catch (InterruptedException e) {
						e.printStackTrace();
					}
 
					// close the progress bar dialog
					progressBar.dismiss();
				}
			  }
		       }).start();
 
	           }
 
                });
 
        }
 
	// file download simulator... a really simple
	public int doSomeTasks() {
 
		while (fileSize <= 1000000) {
 
			fileSize++;
 
			if (fileSize == 100000) {
				return 10;
			} else if (fileSize == 200000) {
				return 20;
			} else if (fileSize == 300000) {
				return 30;
			}
			// ...add your own
 
		}
 
		return 100;
 
	}
 
}
P.S The “doSomeTasks” method is just a file size download simulator, just replace this method with your long running task.

3. Demo

Run the application.
1. Result, a single button.
android progress bar demo1
2. Click on the button, it will prompt a “progress bar dialog” to show the current download progress.
android progress bar demo2
3. Task is completed, progress bar will show 100%, and close automatically.
android progress bar demo3

Download Source Code

Download it – Android-ProgressBar-Example.zip (15 KB)
Read More