我有一個 iOS 應用程式,我前一段時間作業過,它使用的功能我喜歡,并希望以某種方式讓它在我擁有的一些 Android 代碼上作業。
在我的頂部MainActivity我有
SharedPreferences sharedpreferences;
public static final String MyPREFERENCES = "nShownLobby";
在我的onCreate我有
sharedpreferences = getSharedPreferences(MyPREFERENCES, Context.MODE_PRIVATE);
我正在呼叫這個方法
changeTextButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v){
long nb_shown_lobby = PreferenceManager.getDefaultSharedPreferences(MainActivity.this).getLong("nShownLobby", 0);
nb_shown_lobby;
if ((nb_shown_lobby % 20) == 0) {
this.turnAround();
}
int random = (int) (Math.random() * manyDifferentStrings.length);
if (random == oldVaue) {
random = (int) (Math.random() * manyDifferentStrings.length);
}
changingText.setText(manyDifferentStrings[random]);
oldVaue = random;
try {
mySound.start();
} catch (NullPointerException e) {
mySound = MediaPlayer.create(MainActivity.this, R.raw.sound);
}
}
private void turnAround() {
//Do something here
Log.i("Do Something ", "");
}
});
目的是每按 20 次后,該turnAround()方法就會被呼叫,但它不會......它只是被忽略了 - 我猜我錯過了什么?
uj5u.com熱心網友回復:
**According to your question your code should be like this**
private SharedPreferences sharedpreferences;
private SharedPreferences.Editor editor;
private static final String MyPREFERENCES = "nShownLobby";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
sharedpreferences = getSharedPreferences(MyPREFERENCES, Context.MODE_PRIVATE);
editor = sharedpreferences.edit();
changeTextButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v){
int nb_shown_lobby = sharedpreferences.getInt("nShownLobby", 0);
if ((nb_shown_lobby % 20) == 0) {
turnAround();
}
nb_shown_lobby = 1;
editor.putInt("nShownLobby", nb_shown_lobby);
editor.commit();
int random = (int) (Math.random() * manyDifferentStrings.length);
if (random == oldVaue) {
random = (int) (Math.random() * manyDifferentStrings.length);
}
changingText.setText(manyDifferentStrings[random]);
oldVaue = random;
try {
mySound.start();
} catch (NullPointerException e) {
mySound = MediaPlayer.create(MainActivity.this, R.raw.sound);
}
}
});
}
//created this in activity, not in the button onclick
private void turnAround() {
//Do something here
Log.i("Do Something ", "");
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/352787.html
