Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to create a custom preference with a neutral button?

I use the code below to create a custom preference. The xml layout file has a Button, EditText and TextView. This custom layout appears inside an Alert with "OK" and "Cancel" buttons. This all works well.

I would like to add a third button (a neutral button) beside the "OK and "Cancel" buttons. I've experimented with the AlertBuilder class but can't figure out how to incorporate both my custom xml layout and a neutral button.

How can this be done?

Currently have...

public class MelsMessage extends DialogPreference {

    Button bMessage;
    EditText eMessage;
    TextView tMessage;

    public MelsMessage(Context context, AttributeSet attrs) {
        super(context, attrs);
        // TODO Auto-generated constructor stub
    }



    protected View onCreateDialogView() {

        LayoutInflater layoutInflater = LayoutInflater.from(getContext());
        View view = layoutInflater.inflate(R.layout.dialog_pref_mess, null);

        //UI elements

        bMessage = (Button) view.findViewById(R.id.buttonMessage);
        eMessage = (EditText) view.findViewById(R.id.edittextMessage);
        tMessage = (TextView) view.findViewById(R.id.textviewMessage);


        return view;        
    }

}
like image 961
Mel Avatar asked May 04 '11 15:05

Mel


1 Answers

I see your question is a bit old and maybe you already have the answer to your question but here is a solution for your class that extends DialogPreference.

First you have to Override the onPrepareDialogBuilder method in your MelsMessage class:

@Override
protected void onPrepareDialogBuilder(AlertDialog.Builder builder)
{
    super.onPrepareDialogBuilder(builder);
    builder.setNeutralButton("hello", this);
}

this in the setNeutralButton method is DialogInterface.OnClickListener interface that the DialogPreference class implement.

The last thing you have to do is to Override the onClick method in your MelsMessage class:

@Override
public void onClick(DialogInterface dialog, int which)
{
    super.onClick(dialog, which);

    switch (which)
    {
        case DialogInterface.BUTTON_POSITIVE:
            // do things for the right button
            break;

        case DialogInterface.BUTTON_NEGATIVE:
            // do things for the left button
            break;

        default:
            // do things for the center button
            break;
    }
}

If you want to handle the click in another class all you have to do is to implement DialogInterface.OnClickListener in this class.

Hope this will help you. Cheers.

like image 88
WannaGetHigh Avatar answered Nov 05 '22 09:11

WannaGetHigh