如何实现仅首次启动展示一次的Bottom Sheet Dialog弹窗
实现Bottom Sheet Dialog仅展示一次的解决方案
核心逻辑说明
用SharedPreferences存储用户是否已经操作过弹窗的标记,只要用户点击过「同意」或「不同意」任意一个按钮,就将标记设为已操作,下次进入页面时先校验标记,没有操作过才弹窗。之前实现没生效大概率是遗漏了「操作后存储标记」或者「进入页面先校验标记」的步骤。
修改后的完整代码
public class MainActivity extends AppCompatActivity { // 定义SharedPreferences相关常量 private static final String SP_NAME = "app_config"; private static final String KEY_HAS_OPERATED_DIALOG = "has_operated_dialog"; private Button button; private SharedPreferences sp; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); // 初始化SharedPreferences sp = getSharedPreferences(SP_NAME, MODE_PRIVATE); button = findViewById(R.id.nextBtn); // 如果需要进入页面直接弹窗,保留这段判断;如果需要点击按钮才弹窗,把这段移到按钮点击事件里 if (!sp.getBoolean(KEY_HAS_OPERATED_DIALOG, false)) { showBottomSheetDialog(); } button.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { if (!sp.getBoolean(KEY_HAS_OPERATED_DIALOG, false)) { showBottomSheetDialog(); } else { // 已经操作过弹窗直接走对应逻辑 startActivity(new Intent(MainActivity.this, Activity2.class)); finish(); } } }); } // 弹窗逻辑抽成单独方法,避免重复代码 private void showBottomSheetDialog() { BottomSheetDialog bottomSheetDialog = new BottomSheetDialog( MainActivity.this, R.style.BottomSheetDialogTheme); View bottomSheetView = LayoutInflater.from(getApplicationContext()) .inflate(R.layout.layout_bottom_sheet, (LinearLayout) findViewById(R.id.bottomSheetContainer)); bottomSheetDialog.setContentView(bottomSheetView); // 可选配置:禁止点击外部/返回键关闭弹窗,避免用户未操作就关掉弹窗导致标记未存储 bottomSheetDialog.setCancelable(false); bottomSheetDialog.setCanceledOnTouchOutside(false); bottomSheetView.findViewById(R.id.doNotAgree).setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { // 存储已操作标记,如果要求不同意下次还要弹,可以删掉这行存储逻辑 sp.edit().putBoolean(KEY_HAS_OPERATED_DIALOG, true).apply(); bottomSheetDialog.dismiss(); System.exit(0); } }); bottomSheetView.findViewById(R.id.agree).setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { // 存储已操作标记 sp.edit().putBoolean(KEY_HAS_OPERATED_DIALOG, true).apply(); bottomSheetDialog.dismiss(); startActivity(new Intent(MainActivity.this, Activity2.class)); finish(); } }); bottomSheetDialog.show(); } }
注意事项
- 如果要求用户必须同意才能使用APP,不同意就直接退出的话,可以删掉不同意按钮里的存储标记逻辑,这样用户下次打开APP仍然会弹出弹窗
- SharedPreferences的
apply()是异步提交不阻塞主线程,普通场景足够使用,如果需要立即生效可以替换为commit()
内容的提问来源于stack exchange,提问作者Hallies Valentine
相关产品推荐
相关产品推荐

