本文介绍了安卓:我应保持recyclerview里面活动的引用,或有另一种方式?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要使用onBindViewHolder内环境的方法(标准的例子可能是常见的事或的getString的getColor)。到现在为止我已经通过了上下文的构造函数recyclerview并保持在一个变量的引用,但是这对我来说是不好的做法。有越来越情况下动态地从一个recyclerview里面没有把它作为一个变量的一种方式?

 公共SomeRecyclerViewClass(活动活动){
    this.parentActivity =活动;
}


解决方案

我看不到传递上下文在构造函数中的任何缺点,并将其存储在一个领域。反正你可以用这种方式访问​​它:

 公共类MyAdapter扩展RecyclerView.Adapter< MyViewHolder> {    @覆盖
    公共MyViewHolder onCreateViewHolder(ViewGroup中的父母,INT viewType){
        上下文的背景下= parent.getContext();
        //做你的事
    }    @覆盖
    公共无效onBindViewHolder(MyViewHolder持有人,INT位置){
        上下文的背景下= holder.itemView.getContext();
        //做你的事
    }
}

只是为了保持完整性,我后我通常采用的解决方案,它也保持一个参考 LayoutInflater

 公共类MyAdapter扩展RecyclerView.Adapter< MyViewHolder> {    公共语境mContext;
    公共LayoutInflater mInflater;    公共MyAdapter(上下文的背景下){
        mContext =背景;
        mInflater = LayoutInflater.from(上下文);
    }    @覆盖
    公共MyViewHolder onCreateViewHolder(ViewGroup中的父母,INT viewType){
        视图V = mInflater.inflate(R.layout.row,父母,假);
        //做你的事
    }
}

I need to use context methods within the onBindViewHolder (a standard example might be something as common as getString or getColor). Until now I've passed the context to the constructor for the recyclerview and maintained a reference in a variable, however this seems to me to be bad practice. Is there a way of getting context dynamically from inside a recyclerview without storing it as a variable?

public SomeRecyclerViewClass(Activity activity) {
    this.parentActivity = activity;
}
解决方案

I cannot see any downside of passing the Context in the constructor and store it in a field. Anyway you could access it in this way:

public class MyAdapter extends RecyclerView.Adapter<MyViewHolder> {

    @Override
    public MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        Context context = parent.getContext();
        //Do your things
    }

    @Override
    public void onBindViewHolder(MyViewHolder holder, int position) {
        Context context = holder.itemView.getContext();
        //Do your things
    }
}

Just for completeness, I post the solution I usually adopt which keeps also a reference to the LayoutInflater:

public class MyAdapter extends RecyclerView.Adapter<MyViewHolder> {

    public Context mContext;
    public LayoutInflater mInflater;

    public MyAdapter(Context context) {
        mContext = context;
        mInflater = LayoutInflater.from(context);
    }

    @Override
    public MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        View v = mInflater.inflate(R.layout.row, parent, false);
        //Do your things
    }
}

这篇关于安卓:我应保持recyclerview里面活动的引用,或有另一种方式?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-02 17:59