Tuesday, June 7, 2011

Custom AlertDialog

It's a example of custom AlertDialog built using AlertDialog.Builder().

Custom AlertDialog

package com.exercise.AndroidCustomAlertDialog;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.os.Bundle;
import android.view.ViewGroup.LayoutParams;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

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

AlertDialog.Builder myDialog
= new AlertDialog.Builder(AndroidCustomAlertDialog.this);
myDialog.setTitle("My Dialog");

ImageView imageView = new ImageView(AndroidCustomAlertDialog.this);
imageView.setImageResource(R.drawable.icon);
LayoutParams imageViewLayoutParams
= new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
imageView.setLayoutParams(imageViewLayoutParams);

TextView textView = new TextView(AndroidCustomAlertDialog.this);
textView.setText("It's my custom AlertDialog");
LayoutParams textViewLayoutParams
= new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
textView.setLayoutParams(textViewLayoutParams);

EditText editText = new EditText(AndroidCustomAlertDialog.this);
LayoutParams editTextLayoutParams
= new LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.WRAP_CONTENT);
editText.setLayoutParams(editTextLayoutParams);

LinearLayout layout = new LinearLayout(AndroidCustomAlertDialog.this);
layout.setOrientation(LinearLayout.VERTICAL);
layout.addView(imageView);
layout.addView(textView);
layout.addView(editText);

myDialog.setView(layout);

myDialog.setPositiveButton("OK", new DialogInterface.OnClickListener() {
// do something when the button is clicked
public void onClick(DialogInterface arg0, int arg1) {

}
});

myDialog.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
// do something when the button is clicked
public void onClick(DialogInterface arg0, int arg1) {

}
});

myDialog.show();
}
}



Download the files.

2 comments:

  1. This comment has been removed by the author.

    ReplyDelete
  2. I'm the opinion this is a very bad example. You should define your layout in a XML file and then use builder.setView(R.layout.yourXml).

    ReplyDelete