Saturday, February 13, 2010

Create a Custom Dialog

This article helps to creating a custom dialog box.

1. Create a Layout.xml for customDialog
Create a new layout which contains the view. in this example i have used edittext and button.


<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="wrap_content" android:layout_height="wrap_content">

    <EditText android:id="@+id/EditText01" android:layout_height="wrap_content" android:text="Enter your name" android:layout_width="250dip"></EditText>

    <Button android:id="@+id/Button01" android:layout_width="wrap_content"
        android:layout_height="wrap_content" android:text="click"></Button>

</LinearLayout>



2. Create a Custom Dialog Class.
a. Create a class extends the dialog class
b. Create a Event Handler Interface as a member
c. Use the custom layout in onCreate Method.

public class MyCustomDialog extends Dialog {

    public interface ReadyListener {
        public void ready(String name);
    }

    private String name;
    private ReadyListener readyListener;
    EditText etName;

    public MyCustomDialog(Context context, String name,
            ReadyListener readyListener) {
        super(context);
        this.name = name;
        this.readyListener = readyListener;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.mycustomdialog);
        setTitle("Enter your Name ");
        Button buttonOK = (Button) findViewById(R.id.Button01);
        buttonOK.setOnClickListener(new OKListener());
        etName = (EditText) findViewById(R.id.EditText01);
    }

    private class OKListener implements android.view.View.OnClickListener {
        @Override
        public void onClick(View v) {
            readyListener.ready(String.valueOf(etName.getText()));
            MyCustomDialog.this.dismiss();
        }
    }

}


3. Create a MainActivity and Implement the CustomDialog
public class MainActivity extends Activity {
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        MyCustomDialog myDialog = new MyCustomDialog(this, "",
                new OnReadyListener());
        myDialog.show();
    }
    private class OnReadyListener implements MyCustomDialog.ReadyListener {
        @Override
        public void ready(String name) {
            Toast.makeText(MainActivity.this, name, Toast.LENGTH_LONG).show();
        }
    }
}



No comments:

Post a Comment