Jul 24, 2011

Create custom dialog using AlertDialog.Builder, by inflating XML

Example:
Create custom dialog using AlertDialog.Builder, by inflating XML

Create a XML file of custom layout, /res/layout/mylayout.xml.
<?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"
>
<AnalogClock
android:layout_width="wrap_content"
android:layout_height="wrap_content"
/>
<Button
android:id="@+id/idButton"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="Button"
/>
</LinearLayout>


package com.AndroidCustomDialog;

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.widget.Button;
import android.widget.Toast;

public class AndroidCustomDialogActivity extends Activity {

void openCustomDialog(){
AlertDialog.Builder customDialog
= new AlertDialog.Builder(AndroidCustomDialogActivity.this);
customDialog.setTitle("Custom Dialog");

LayoutInflater layoutInflater
= (LayoutInflater)getApplicationContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View view=layoutInflater.inflate(R.layout.mylayout,null);

Button btn = (Button)view.findViewById(R.id.idButton);
btn.setOnClickListener(new Button.OnClickListener(){

@Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
Toast.makeText(getApplicationContext(), "Button Pressed", Toast.LENGTH_LONG).show();
}});

customDialog.setPositiveButton("OK", new DialogInterface.OnClickListener(){

@Override
public void onClick(DialogInterface arg0, int arg1) {
// TODO Auto-generated method stub

}});

customDialog.setNegativeButton("Cancel", new DialogInterface.OnClickListener(){

@Override
public void onClick(DialogInterface arg0, int arg1) {
// TODO Auto-generated method stub

}});

customDialog.setView(view);
customDialog.show();
}

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



Related Post:
- Create custom dialog using AlertDialog.Builder, with dynamic content

2 comments:

Infolinks In Text Ads