片段内的SharedPreferences

时间:2016-07-12 16:41:09

标签: android-fragments sharedpreferences

一旦用户从另一个片段的列表中选择一个项目,它就会将您带到此片段。我在尝试保存所选用户评级时遇到问题。当用户返回时,它应该与之前选择的评级相同。

    @property
    def index_const(self):
        if hasattr(self, '_m_index_const'):
            return self._m_index_const

        self._m_index_const = self._root.header.consts[(self.idx - 64)];
        return self._m_index_const

为什么我不能使用"这个"

import android.content.SharedPreferences;
import android.preference.PreferenceManager;
import android.support.v4.app.Fragment;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.RatingBar;
import android.widget.TextView;
import java.util.Arrays;

public class infoFragment extends Fragment {

    TextView degrees;
    ImageView image;
    String stringtext;
    String [] hold;
    private RatingBar rating;
    SharedPreferences wmbPreference1;
    SharedPreferences.Editor editor;


    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,    Bundle savedInstanceState) {
        return inflater.inflate(R.layout.info_layout, container, false);
    }
    @Override
    public void onViewCreated(View view, Bundle savedInstanceState){
        image = (ImageView) view.findViewById(R.id.imageView);

我应该在条件语句中调用onRatingChanged来保存吗?

rating =((RatingBar) view.findViewById(R.id.ratingBar)).setOnRatingBarChangeListener(this);
            wmbPreference1 = PreferenceManager.getDefaultSharedPreferences(this);
            degrees =(TextView)view.findViewById(R.id.textView);

        }

    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);
    }
    public void setText(final String string) {
       Character[] hold;
        if(string == "apple"){
            String[] word = { " A \n", "B\n" };

            degrees.setText(Arrays.toString(word).replaceAll("\\[|\\]", ""));;
            image.setImageResource(R.drawable.APPLE);
        }

1 个答案:

答案 0 :(得分:0)

您的Fragment应该实施OnRatingBarChangeListener

public class infoFragment extends Fragment implements OnRatingBarChangeListener

另一件事是setOnRatingChangeListener没有返回值,因此您无法像往常一样将返回值分配给rating

你应该这样做:

rating = (RatingBar) view.findViewById(R.id.ratingBar); 
rating.setOnRatingBarChangeListener(this);