Android自定义AlertDialog中自定义按钮失效,求点击关闭实现方案
Let's get your custom dialog button working properly. There are a few small gaps in your current code that are preventing the button from dismissing the dialog—let's fix them step by step:
Key Issues in Your Current Code
- You aren't storing the created
AlertDialoginstance, so you can't calldismiss()on it later - You haven't referenced the custom button from your
activity_dialoglayout to set a click listener - You forgot to update the
firstStartpreference tofalse, so the dialog will keep popping up every time the app launches
Modified Working Code
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() { // Inflate your custom dialog layout View customLayout = getLayoutInflater().inflate(R.layout.activity_dialog, null); // Build the dialog and store the instance AlertDialog dialog = new AlertDialog.Builder(MainActivity.this, R.style.DialogCustomTheme) .setView(customLayout) .setCancelable(false) .create(); // Find your custom button from the dialog layout (replace R.id.your_custom_button with actual ID) Button customDialogButton = customLayout.findViewById(R.id.your_custom_button); // Set click listener to dismiss the dialog customDialogButton.setOnClickListener(v -> { dialog.dismiss(); // Update the preference so the dialog doesn't show again SharedPreferences prefs = getSharedPreferences("prefs", MODE_PRIVATE); SharedPreferences.Editor editor = prefs.edit(); editor.putBoolean("firstStart", false); editor.apply(); }); // Show the dialog dialog.show(); } }
Important Notes
- Replace
R.id.your_custom_button: Make sure to use the actual ID of the button in youractivity_dialog.xmllayout file. - Saving
firstStart: We now setfirstStarttofalsewhen the button is clicked, so the dialog only appears on the first app launch. - Storing the Dialog Instance: By storing the
AlertDialogobject when we create it, we can calldismiss()directly from the button's click listener to close the dialog.
That's it—your custom button should now close the dialog properly when tapped!
内容的提问来源于stack exchange,提问作者Teja
相关产品推荐
相关产品推荐

