Custom dialogs
Dialogs are small windows that appear in front of the
current user interface. Progress Dialogs, DatePicker and TimePicker dialogs and
Alert Dialogs are the dialogs that can be designed. They are used as
notifications, for performing small tasks etc. Unlike Toast messages, the
dialogs accepts user interactions.
Creating a Custom Dialog helps the user in creating their
own layout for the dialog window. The layout can be defined with layout and
widget elements. Then pass the resource ID of the layout to
setContentView(View).
Creating a Custom Dialog
Ø
Create
an xml layout for the Custom dialog and save as dialog.xml.
This is the code for dialog.xml
file:
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/layout_root"
android:orientation="horizontal"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:padding="10dp"
>
<ImageView android:id="@+id/image"
android:layout_width="wrap_content"
android:layout_height="fill_parent"
android:layout_marginRight="10dp"
/>
<TextView android:id="@+id/text"
android:layout_width="wrap_content"
android:layout_height="fill_parent"
android:textColor="#FFF"
/>
</LinearLayout>
Ø
Now
define the Dialog and set title and content view.
Dialog dialog = new Dialog(currentContext);
dialog.setContentView(R.layout.custom_dialog);
dialog.setTitle("Custom
Dialog");
Ø
Now
define the TextView and ImageView contents inside your Activity class.
TextView text = (TextView)
dialog.findViewById(R.id.text);
text.setText("Hello, this is
a custom dialog!");
ImageView image = (ImageView)
dialog.findViewById(R.id.image);
image.setImageResource(R.drawable.android);
Ø
Complete
code for the Activity class is given below:
package com.ipsr.customdialog;
import android.app.Activity;
import android.app.Dialog;
import android.content.Context;
import android.os.Bundle;
import android.widget.ImageView;
import android.widget.TextView;
public class CustomDialogActivity
extends Activity {
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
Dialog dialog = new Dialog(this);
dialog.setContentView(R.layout.dialog);
dialog.setTitle("Custom
Dialog");
TextView text = (TextView)
dialog.findViewById(R.id.text);
text.setText("Hello, this is a
custom dialog!");
ImageView image = (ImageView)
dialog.findViewById(R.id.image);
image.setImageResource(R.drawable.ic_launcher);
dialog.show();
}
}
No comments:
Post a Comment