我现在已经获得了所有代码,但一直在崩溃。基本上,代码是一个按钮,单击该按钮时,会在金额中添加一个数字。因此,单击一次时,它将为 1;再次单击将变为 2,然后是 3,以此类推,就像一个股票行情一样。
package com.example.counter;
import android.app.Activity;
import android.content.SharedPreferences;
import android.os.Bundle;
public class MainActivity extends Activity {
// Private member field to keep track of the count
private int mCount = 0;
public static final String PREFS_NAME = "com.example.myApp.mCount";
private SharedPreferences settings = null;
private SharedPreferences.Editor editor = null;
/** ADD THIS METHOD **/
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState); // Always call the superclass method first
settings = getSharedPreferences(PREFS_NAME, MODE_PRIVATE);
}
@Override
public void onPause() {
super.onPause(); // Always call the superclass method first
mCount = settings.getInt("mCount", 0);
}
@Override
public void onResume() {
super.onResume(); // Always call the superclass method first
editor = settings.edit(); /** ADD THIS LINE **/
editor.putInt("mCount", mCount);
editor.commit();
}
}
xml:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity" >
<TextView
android:id="@+id/TextViewCount"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:layout_centerVertical="true"
android:text="@string/hello_world" />
<Button
android:id="@+id/ButtonCount"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_above="@+id/TextViewCount"
android:layout_alignRight="@+id/TextViewCount"
android:layout_marginBottom="22dp"
android:text="Count" />
</RelativeLayout>