如何在重新加载时退出并恢复时,如何使其工作并保存

时间:2013-02-10 14:12:09

标签: java android function save

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

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 layout

<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>

2 个答案:

答案 0 :(得分: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();
}

答案 1 :(得分: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,耗尽电池电量。