erikbstack
erikbstack

Reputation: 13244

Android: creating a dialog

I think I followed the Android tutorial quite closely here. I have a ListActivity which calls a showDialog(DIALOG_EXPORT); at some point. My onCreateDialog() creates a dialog, sets an xml view and then tries to do something with the elements of that dialog, but directly after findViewById() everything is null. Why?

here the code:

protected Dialog onCreateDialog(int id) {
    switch(id){
    case DIALOG_EXPORT:
        final Dialog dial = new Dialog(this);
        dial.setContentView(R.layout.export_dialog);
        dial.setTitle(R.string.dialog_export_title);
        EditText eFile = (EditText) findViewById(R.id.e_dialog_export);
        Button bOkay = (Button) findViewById(R.id.b_export_okay);
        Button bCancel = (Button) findViewById(R.id.b_export_cancel);
        <here all View elements are empty>
        ...
        return dial;

    ...
    }
}

Upvotes: 0

Views: 99

Answers (3)

Vineet Shukla
Vineet Shukla

Reputation: 24021

You need to inflate the view. You need to do something like this:

@Override
protected Dialog onCreateDialog(int id) {

    LayoutInflater inflator = LayoutInflater.from(context);
    View view = inflator.inflate(R.layout.yourview, null);
    Button positive = (Button)view.findViewById(R.id.btn_positive);
    Button negative = (Button)view.findViewById(R.id.btn_negative);

    positive.setOnClickListener(new Button.OnClickListener(){
        public void onClick(View v) {
            removeDialog(0);
        }
    });

    negative.setOnClickListener(new Button.OnClickListener(){
        public void onClick(View v) {
            removeDialog(0);
        }
    });

    AlertDialog dialog = new AlertDialog.Builder(this).create();
    dialog.setView(view);

    return dialog;
}

Upvotes: 1

DRiFTy
DRiFTy

Reputation: 11369

You need to use dial.findViewById() instead of just findViewById()

Upvotes: 2

Steve Bergamini
Steve Bergamini

Reputation: 14600

You forgot to inflate the layout of the dialog per the tutorial. Have another look at it. It's in there. Without inflating the layout, those other views will come back null.

Upvotes: 0

Related Questions