Wednesday, 3 July 2013

Displaying a Dialog Window Using an Activity


  1. Using Eclipse create a new Android project and name it Dialog
  2. Add the following statements in bold to the mainactivity.xml

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:orientation="vertical"
    android:layout_height="fill_parent"
    android:layout_width="fill_parent"
    tools:context=".MainActivity" >

    <TextView
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:text="@string/hello_world" />
    <Button 
        android:id="@+id/btn_dialog"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:hint="@string/click"
        />
</LinearLayout>

3.Add the following statement in to the MainActivity.java file


package com.dialog;

import android.os.Bundle;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.DialogInterface;
import android.view.Menu;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;

public class MainActivity extends Activity {

CharSequence[] items={"Google","Apple","Htc"};
boolean[] itemsChecked=new boolean[items.length];
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button btn=(Button) findViewById(R.id.btn_dialog);
btn.setOnClickListener(new View.OnClickListener() {

@Override
public void onClick(View v) {
// TODO Auto-generated method stub
showDialog(0);
}
});
}


@Deprecated
protected Dialog onCreateDialog(int id) {
// TODO Auto-generated method stub
switch (id) {
case 0:
return new AlertDialog.Builder(this).setIcon(R.drawable.ic_launcher).setTitle("My Dialog box....")
.setPositiveButton("OK",new DialogInterface.OnClickListener() {

@Override
public void onClick(DialogInterface dialog, int which) {
// TODO Auto-generated method stub
Toast.makeText(getBaseContext(), "OK Clicked...",Toast.LENGTH_SHORT).show();
}
}).setNegativeButton("Cancel",new DialogInterface.OnClickListener() {

@Override
public void onClick(DialogInterface dialog, int which) {
// TODO Auto-generated method stub
Toast.makeText(getBaseContext(), "Cancel Clicked...",Toast.LENGTH_SHORT).show();
}
}).setMultiChoiceItems(items, itemsChecked, new DialogInterface.OnMultiChoiceClickListener() {

@Override
public void onClick(DialogInterface dialog, int which, boolean isChecked) {
// TODO Auto-generated method stub
Toast.makeText(getBaseContext(), items[which]+(isChecked?"checked !":"unchecked !"),Toast.LENGTH_SHORT).show();
}
}).create();



}

return null;
}

}







No comments:

Post a Comment