Customed AlertDialog in Android

less than 1 minute read

You can easily customize AlertDialog and can be wrapped with function.

//------------------------------------
// Inflater
//------------------------------------
LayoutInflater inflater = (LayoutInflater) mActivity.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View mView = inflater.inflate(R.layout.alert_record, null, false);

I highly recommend to use inflate layout file rather than setting programmatically. It’s more readable and shorten the source code.

alert.setPositiveButton(getResources().getString(R.string.disp_ok), new DialogInterface.OnClickListener() {
    @Override
    public void onClick(DialogInterface dialog, int which) {
        dialog.dismiss();
    }
});

Builder has also setNegativeButton, setNeutralButton functions. This means that AlertDialog can have 3 buttons. But don’t worry. We can easily add user-defined buttons and other controls.

Full source

private void showAlert() {

    AlertDialog.Builder alert = new AlertDialog.Builder(this);

    final Context context = this;

    String title = getResources().getString(R.string.msg_gameover);
    String message = "";
    //------------------------------------
    // Inflater
    //------------------------------------
    LayoutInflater inflater = (LayoutInflater) mActivity.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
    View mView = inflater.inflate(R.layout.alert_record, null, false); // ScrollView

    //------------------------------------
    // Views
    //------------------------------------
    final ImageView iv = (ImageView) mView.findViewById(R.id.alert_iv_record);

    final TextView tvTodayHigh = (TextView) mView.findViewById(R.id.alrec_tv_todayhigh);
    tvTodayHigh.setText(String.format("%s", "TEST"));

    // ----------------------------------------
    // Set Dialog
    // ----------------------------------------
    alert.setView(mView);

    alert.setPositiveButton(getResources().getString(R.string.disp_ok), new DialogInterface.OnClickListener() {
        @Override
        public void onClick(DialogInterface dialog, int which) {
            dialog.dismiss();
        }
    });

    alert.setMessage(title);
    alert.setCancelable(true);
    alert.show();
}

Tags:

Categories:

Updated:

Leave a comment