1

现在我的按钮计数器工作了,点击时它会增加,但我现在的问题是它不会保存,所以当它重新打开时它会重新开始......我把我的代码放在下面,但任何帮助添加保存功能都会不胜感激!

package com.example.counter;

import android.app.Activity; import android.os.Bundle; import android.view.View; import         android.view.View.OnClickListener; import android.widget.Button; import     android.widget.TextView;

public class MainActivity extends Activity {

// Private member field to keep track of the count
private int mCount = 0;

/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);

final TextView countTextView = (TextView) findViewById(R.id.TextViewCount);
final Button countButton = (Button) findViewById(R.id.ButtonCount);

countButton.setOnClickListener(new OnClickListener() {

    public void onClick(View v) {
        mCount++;
        countTextView.setText("Count: " + mCount);
    }
});

}
}

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/ButtonCount"
    android:layout_alignRight="@+id/ButtonCount"
    android:layout_marginBottom="61dp"
    android:text="Count" />

</RelativeLayout>
4

2 回答 2

0

重载 onPause 方法并使用 SharedPreferences 类保存变量。您还需要重载 onResume 方法以将该值重新加载到 mCount 中。

请阅读:http: //developer.android.com/training/basics/activity-lifecycle/pausing.html

public static final String PREFS_NAME = "com.example.myApp.mCount";
private SharedPreferences settings = getSharedPreferences(PREFS_NAME, MODE_PRIVATE);
private SharedPreferences.Editor editor = settings.edit();

@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.putInt("mCount", mCount);
    editor.commit();
}
于 2013-02-10T14:16:34.113 回答
0

此链接将为您提供帮助。它是存储数据的最简单方法 http://developer.android.com/guide/topics/data/data-storage.html#pref

您将在 onCreate 读取计数器数据并将其保存在 onPause 以便当您的用户再次打开应用程序时它可以很好地恢复。更多详情请访问http://developer.android.com/reference/android/app/Activity.html

不要在每次单击按钮时保存计数器,它会为您的简单任务带来过多的 I/O,从而耗尽电池。

于 2013-02-10T14:17:24.737 回答