简体   繁体   English

android从textview保存一个值

[英]android saving a value from a textview

我制作了一个简单的计数应用程序,其中包含包含计数数字的“文本”视图,并且我想保存计数数字,以便在我关闭该应用程序时,计数数字应该在其中。

You should use SharedPreferences . 您应该使用SharedPreferences Save the count to preference every time it is updated. 每次更新时,将计数保存到首选项。 Read and load the saved value in TextView when app starts next time. 下次启动应用程序时,读取并在TextView加载保存的值。

The best solution for your problem is to use SharedPreference. 针对您的问题的最佳解决方案是使用SharedPreference。 create another class called SaveCounterValue and copy the following code to that class 创建另一个名为SaveCounterValue的类,并将以下代码复制到该类

public class SaveCounterValue { 公共类SaveCounterValue {

static final String PREF_COUNTER= "counter";
static SharedPreferences getSharedPreferences(Context ctx) {
    return PreferenceManager.getDefaultSharedPreferences(ctx);
}

public static void setCounter(Context ctx, int counter)
{
    SharedPreferences.Editor editor = getSharedPreferences(ctx).edit();
    editor.putInt(PREF_COUNTER, counter);
    editor.commit();
}

public static Long getCounter(Context ctx)
{
    return getSharedPreferences(ctx).getInt(PREF_COUNTER, 0);
}

} }

Then in your activity after conter++ you copy the below code 然后在conter ++之后的活动中,复制以下代码

SaveCounterValue.setConuter(context, counter); SaveCounterValue.setConuter(context,counter);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM