我将如何使用共享偏好保存评级?

How would I save the rating with a Shared Preference?

我正在尝试在 AlertDialog 中实现评级栏。我有评级栏工作,但我似乎无法让 SharedPreference 工作以记住事先输入的星级。 Where/How 我应该设置 SharedPreference 才能让它工作吗?

下面是评级 AlertDialog 的代码:

 private float rateValue;

  rating.setOnClickListener(clk ->{
           AlertDialog.Builder mBuild = new AlertDialog.Builder(SoccerItemDetailHostActivity.this);
           mBuild.setTitle("Please rate the app");
           View mView = getLayoutInflater().inflate(R.layout.soccerratingbar,null);

           final RatingBar ratebar = (RatingBar)mView.findViewById(R.id.ratingBar);
           ratebar.setOnRatingBarChangeListener(new RatingBar.OnRatingBarChangeListener() {
               @Override
               public void onRatingChanged(RatingBar ratingBar, float rating, boolean fromUser) {
                   rateValue = rating;
                   Toast.makeText(SoccerItemDetailHostActivity.this, ""+rating, Toast.LENGTH_SHORT).show();
               }
           });

           Button btnSubmit=(Button)mView.findViewById(R.id.btnSubRating);
           btnSubmit.setOnClickListener(new View.OnClickListener() {
               @Override
               public void onClick(View v) {
                   Toast.makeText(SoccerItemDetailHostActivity.this, ""+rateValue, Toast.LENGTH_SHORT).show();
               }
           });
           mBuild.setView(mView);
           AlertDialog dialog=mBuild.create();
           dialog.show();

       });

I have the rating bar working but I can't seem to make the SharedPreference work to remember what star rating was inputted beforehand.

嗯,你试过什么?您的代码没有显示任何使用 SharedPreferences 的尝试,因此无法说出您做错了什么。

Where/How should I put the SharedPreference to make it work?

您或许可以在保存当前评分的对话框中添加一个 onDismissListener。

要保存评分,您需要将其保存在 SharedPreferences 中。在下面的代码中,我向您展示了如何实现这一点:

RatingBar ratingBar = findViewById(R.id.ratingbar);
        if(getRating(getApplicationContext()) != 0){
            ratingBar.setRating(getRating(getApplicationContext()));
        }
        ratingBar.setOnRatingBarChangeListener((ratingBar1, rating, fromUser) -> {
                setRatingBar(getApplicationContext(),rating);

        });

这里提到的 SharedPreferences 函数:

public static SharedPreferences prefs(Context context){
        return PreferenceManager.getDefaultSharedPreferences(context);
    }
    public static void setRatingBar(Context context, float Float) {
        prefs(context).edit().putFloat("RatingBar", Float).apply();
    }
    public static float getRating(Context context) {
        return prefs(context).getFloat("RatingBar", 0);
    }