您好,我是 android 新手,实际上我正在开发一个应用程序,用户将在该应用程序上单击一个按钮,并且该按钮应记录单击事件 - 每次单击该按钮时计数器应递增。该按钮将显示在一个活动中,一旦用户单击该按钮,将显示另一个活动,从而显示结果。
实际上,我在将 sharedPreferences 分配给按钮然后将其显示到下一个活动中时遇到问题,因此有点击次数。
我正在使用的代码如下:
MainActivity.java
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
public class MainActivity extends Activity {
/** Called when the activity is first created. */
/** Declare the variables being used */
public static final String GAME_PREFERENCES = "GamePrefs";
public static final String GAME_PREFERENCES_SCORE = "Score"; // Integer
int counter;
Button add;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
counter = 0;
add = (Button) findViewById (R.id.bAdd);
add.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// TODO Auto-generated method stub
counter++;
Intent openClickActivity2 = new Intent("com.android.jay.Results");
startActivity(openClickActivity2);
}
});
}
}
结果.java
import android.content.Context;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.widget.TextView;
public class Results extends MainActivity{
public void onCreate(Bundle savedInstanceState) {
SharedPreferences mGameSettings;
super.onCreate(savedInstanceState);
mGameSettings = getSharedPreferences(GAME_PREFERENCES, Context.MODE_PRIVATE);
setContentView(R.layout.results);
final TextView DisplayResults =
(TextView) findViewById(R.id.bAdd);
if (mGameSettings.contains(GAME_PREFERENCES_SCORE)) {
DisplayResults.setText(mGameSettings.getString(GAME_PREFERENCES_SCORE, “counter”));
}
}
}
任何指导我的帮助将不胜感激。谢谢