简体   繁体   English

当我们在 Android 上打开应用程序时,仅在第三次显示 toast

[英]Showing toast only at a third time, when we open the app on Android

I'm trying to create simple toast which will show only at the third time, when we open the app.我正在尝试创建仅在第三次打开应用程序时才显示的简单吐司。 Tried to google that question, but nothing found.试图谷歌这个问题,但没有找到。 Help me please.请帮帮我。

public class MainActivity extends AppCompatActivity {

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    Context context = getApplicationContext();
    CharSequence text = "Hello toast!";
    int duration = Toast.LENGTH_SHORT;

    Toast toast = Toast.makeText(context, text, duration);
    toast.show();
}

} }

So you need a counter the increments on starting the app and also gets checked if it reached the number 3. For this question I assume that MainActivity will be the first Activity that will be shown on startup and it is the only activity.因此,您需要一个计数器来计算启动应用程序时的增量,并检查它是否达到数字 3。对于这个问题,我假设MainActivity将是启动时显示的第一个 Activity,并且它是唯一的 Activity。 Otherwise you must do some adjustments, when it is possible to navigate to another Activity and back.否则,当可以导航到另一个活动并返回时,您必须进行一些调整。

private final String PREF_COUNTER_KEY = "PREF_COUNTER_KEY";

@Override
protected void onCreate(Bundle savedInstanceState) {
   super.onCreate(savedInstanceState);
   setContentView(R.layout.activity_main);
   
   // load counter 
   SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(MainActivity.this);  
   int startupCounter = prefs.getInt(PREF_COUNTER_KEY, 0);  
   startupCounter++;

   if(startupCounter > 2){
      Toast toast = Toast.makeText(getApplicationContext(), "Hello toast!", Toast.LENGTH_SHORT).show();
   }  
 
   // save incrementation
   SharedPreferences.Editor prefsEditor = prefs.edit();
   prefsEditor.putInt(PREF_COUNTER_KEY, counter);
   prefsEditor.apply();

}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM