[英]On a button click I want to display a toast message
I want that this message is displayed only the first three times this button is clicked and never after that even if the application is restarted, I want to know the best way to achieve it. 我希望仅在单击此按钮的前三下显示此消息,并且即使在重新启动应用程序之后也不要在此之后显示此消息,我想知道实现此消息的最佳方法。 I plan to make a DB and enter values in that DB on button press and place my toast logic inside of an if statement.
我计划制作一个数据库,并在按下按钮时在该数据库中输入值,并将我的Toast逻辑放在if语句内。 I want to know if there is a better way to do it without using a DB.
我想知道是否有更好的方法可以不使用数据库。
If by better you mean easier then you can use the SharedPreferences mechanism. 如果更好地意味着您更轻松,那么可以使用SharedPreferences机制。
The shared preferences is basically a property set that is common for your entire activity or can be used by each activity separately. 共享首选项基本上是整个活动共有的属性集,或者可以由每个活动单独使用。
class Listener implements OnClickListener{
final private SharedPreferences prefs;
Listener(SharedPreferences prefs){
this.prefs=prefs;
}
public void onClick(View view) {
int count = prefs.getInt("toastCount",0);
if(count>=3) return;
//do something else here
SharedPreferences.Editor editor = prefs.edit();
editor.putInt("toastCount", count+1);
editor.commit();
}
}
and you can initiate this listnener using the getPreferences()
or getSharedPreferences()
methods from your activity 您可以使用活动中的
getPreferences()
或getSharedPreferences()
方法来启动此侦听器
i think Shared Preferences is better than DB. 我认为共享首选项比数据库更好。
You just add count(int)
in shared Prefernces. 您只需在共享的首选项中添加
count(int)
。
You can use this code: 您可以使用以下代码:
button.setOnClickListener(new OnClickListener() {
public void onClick(View view) {
Toast.makeText(app.getBaseContext(),"Your message",
Toast.LENGTH_SHORT).show();
}
}); });
Consider persisting your data somewhere in the memory. 考虑将数据保留在内存中的某个位置。 Trivial data like this should not go into the database.
这样的琐碎数据不应该进入数据库。 It would be a bad decision.
这将是一个错误的决定。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.