如何从recyclerView适配器访问SharedPrefences?

时间:2018-05-04 20:09:45

标签: android android-recyclerview sharedpreferences recycler-adapter

我想从我的适配器访问SharedPrefences,因为我想检查一个变量来设置ImageView可见或消失。

class MainAdapter extends RecyclerView.Adapter<MainAdapter.ViewHolder> implements View.OnClickListener, View.OnLongClickListener{


ArrayList<String> mData;
public ImageView mMinus;
public static final String SHARED_PREFS_DATA = "sharedPrefsData";



public MainAdapter(ArrayList<String> data) {
        mData = data;
}



@NonNull
@Override
public MainAdapter.ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
    View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.row, parent, false);
    return new ViewHolder(view);
}

@Override
public void onBindViewHolder(@NonNull MainAdapter.ViewHolder holder, int position) {
    holder.mText.setText(mData.get(position));

    SharedPreferences sharedPreferences = getSharedPreferences(SHARED_PREFS_DATA, 0);
    int a = sharedPreferences.getInt("visible", 0);
    if(a == 0)
       holder.mMinus.setVisibility(View.GONE);
    else
       holder.mMinus.setVisibility(View.VISIBLE); 

}

错误:找不到符号方法getSharedPreferences(String,int)

1 个答案:

答案 0 :(得分:3)

1.从context发送Activityadapter并使用此context您可以访问shared preferences

2.您也可以传递Activity引用而不是Context