我想从我的适配器访问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)
答案 0 :(得分:3)
1.从context
发送Activity
到adapter
并使用此context
您可以访问shared preferences
2.您也可以传递Activity
引用而不是Context