Android studio共享首选项存储到设备存储

问题描述 投票:0回答:1

我是一个新的Android应用程序开发人员。我正在制作一个应用程序,我想使用共享首选项存储余额整数,但我不知道该怎么做。我做了很多谷歌搜索,我仍然感到困惑。任何人都可以把共享首选项存储在我的代码中的余额整数?这是代码。

import android.content.SharedPreferences;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.view.WindowManager;
import android.widget.ImageButton;
import android.widget.TextView;

public class MainActivity extends AppCompatActivity {
    int balance = 0;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        //Hide notification bar
        getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
        //Click counter
        final TextView text = (TextView) findViewById(R.id.balance_text);
        assert text != null;
        text.setText(balance + " $");
        final ImageButton button = (ImageButton) findViewById(R.id.click_button);
        assert button != null;
        button.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                balance++;
                text.setText("" + balance + " $");
            }
        });
    }

}
java android
1个回答
2
投票

请查找以下代码以获取sharedpreferences中的值

public class MainActivity extends AppCompatActivity {
int balance;;
private SharedPreferences preferences;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    //Hide notification bar
    getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
    //Click counter
    final TextView text = (TextView) findViewById(R.id.balance_text);
    assert text != null;
    // to retreuve the values from the shared preference
    preferences = PreferenceManager.getDefaultSharedPreferences(this);
    balance = preferences.getInt("balance", 0);
    text.setText(balance + " $");
    final ImageButton button = (ImageButton) findViewById(R.id.click_button);
    assert button != null;
    button.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View v) {
            balance++;
            text.setText("" + balance + " $");
        }
    });
}

}

使用这些行保存到共享首选项。你可以在onBackPressed()上使用它

@Override
public void onBackPressed() {
    super.onBackPressed();
    SharedPreferences.Editor editor = preferences.edit();
        editor.putInt("balance", balance);
        editor.apply();
}
© www.soinside.com 2019 - 2024. All rights reserved.