你如何在评级栏中保存用户评级?

时间:2014-05-18 07:36:51

标签: java android ratingbar

大家好:)我有一个评级栏,但它可以工作但是当用户离开页面时评级不会保存。你如何保存用户评级?

以下是代码

RatingBar ratingBar;
TextView ratingText;
SharedPreferences wmbPreference1;    
SharedPreferences.Editor editor;

@Override
protected void onCreate(Bundle savedInstanceState) {        
       super.onCreate(savedInstanceState);
       setContentView(R.layout.list_item_activity_1);       
       ratingText = (TextView) findViewById(R.id.rating);
       ((RatingBar) findViewById(R.id.ratingBar1)).setOnRatingBarChangeListener(this);    
       wmbPreference1 = PreferenceManager.getDefaultSharedPreferences(this);
}

@Override
public void onRatingChanged(RatingBar ratingBar, float rating,
boolean fromTouch) {    
       final int numStars = ratingBar.getNumStars();
       editor = wmbPreference1.edit();
       editor.putInt("numStars", numStars);
       editor.commit();  
       int ratings = wmbPreference1.getInt("numStars", 0);
       ratingText.setText(rating + "/" + ratings.toString());
}

我们将不胜感激。

1 个答案:

答案 0 :(得分:0)

您可以使用 SharedPreferences ...

在离开应用程序之前将评分保存在SharedPreferences并从SharedPreferences检索评级,并在您返回应用程序时将其设置在评级栏中。

SharedPreferences wmbPreference1,wmbPreference2;    
SharedPreferences.Editor editor;

//wmbPreference for Shared Prefs that lasts forever
wmbPreference1 = PreferenceManager.getDefaultSharedPreferences(this);  

//installsp for Shared Prefs that lasts only just once each time program is running
wmbPreference2 =getApplicationContext().getSharedPreferences("MYKEY",Activity.MODE_PRIVATE);

保存值

SharedPreferences.Editor editor = wmbPreference1.edit();
editor.putString("MYKEY", "12345");
editor.commit();

您可以检索值,如

String Phonenumber = wmbPreference1.getString("MYKEY", "");

MYKEY 键名,您可以通过它来识别值。

<小时/> 的修改


像这样更改你的代码

SharedPreferences wmbPreference1;    
SharedPreferences.Editor editor;
@Override
protected void onCreate(Bundle savedInstanceState) {    
super.onCreate(savedInstanceState);
setContentView(R.layout.list_item_activity_1);  
ratingText = (TextView) findViewById(R.id.rating);
((RatingBar) findViewById(R.id.ratingBar1))
.setOnRatingBarChangeListener(this);  
wmbPreference1 = PreferenceManager.getDefaultSharedPreferences(this);      
}

@Override
public void onRatingChanged(RatingBar ratingBar, float rating,
boolean fromTouch) {
final int numStars = ratingBar.getNumStars();
editor = wmbPreference1.edit();
editor.putInt("numStars", numStars);
editor.commit();

当你回来时,也就是当你想要检索评级时

int ratings = wmbPreference1.getInt("numStars", 0);
ratingText.setText(rating + "/" + String.valueOf(ratings));

此处ratings将保留之前设定的评分。