Skip to content
Advertisement

How to make Custom button work in custom alert Dialog Box using android

public class MainActivity extends AppCompatActivity
{
    private TextView regis;
    public Button bt_ok;
    @Override
    protected void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        bt_ok=findViewById(R.id.bt_ok);
        getSupportActionBar().hide();
        SharedPreferences prefs = getSharedPreferences("prefs", MODE_PRIVATE);
        boolean firstStart = prefs.getBoolean("firstStart", true);
        if (firstStart)
        {
            showStartDialog();
        }
    }
    public void showStartDialog()
    {
        LayoutInflater inflater = LayoutInflater.from(this);
        View view =inflater.inflate(R.layout.activity_dialog,null);
        final AlertDialog.Builder dialog= new AlertDialog.Builder(MainActivity.this,R.style.DialogCustomTheme);
        final View customLayout = getLayoutInflater().inflate(R.layout.activity_dialog,null);
        dialog.setView(customLayout).create();
        dialog.setCancelable(false);
        dialog.show();
        SharedPreferences prefs = getSharedPreferences("prefs", MODE_PRIVATE);
        SharedPreferences.Editor editor = prefs.edit();
        editor.apply();
        }
}

I am unable to make the custom button work , my requirement is simple when my custom dialog box is opened i have to dismiss it by simply clicking on button i dont want to use in-built alert dialog box buttons.Please help me thankyou in advance.

Advertisement

Answer

Declare your button xml on the dialog then setOnclickListener on that button

public void showStartDialog()
{

    final AlertDialog.Builder dialog= new AlertDialog.Builder(MainActivity.this,R.style.DialogCustomTheme);
    final View customLayout = getLayoutInflater().inflate(R.layout.activity_dialog,null);

     Button btn = customLayout.findViewById(R.id.your_btn_xml);

    dialog.setView(customLayout).create();
    dialog.setCancelable(false);
    
    SharedPreferences prefs = getSharedPreferences("prefs", MODE_PRIVATE);
    SharedPreferences.Editor editor = prefs.edit();
    editor.apply();

    AlertDialog alertDialog = dialog.create();
    alertDialog.show();

    btn.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            //do something when clicked
            alertDialog.dismiss();
        }});
}
Advertisement