Android: should I maintain a reference to the activity inside a recyclerview or is there another way?

烈酒焚心 提交于 2019-12-06 07:19:54

问题


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;
}

回答1:


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
    }
}



回答2:


You could have a context in application class and can have a static method to get that context.

public class MyApp extends android.app.Application {

private static MyApp instance;

public MyApp() {
    instance = this;
}

public static Context getContext() {
    return instance;
}}



回答3:


You can do like this :

private Context context;

@Override
    public MessageViewHolder onCreateViewHolder(ViewGroup viewGroup, int i) {

        View v = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.layout_message_pictures, null);

        context = v.getContext();

        return new MessageViewHolder(v);
    }


来源:https://stackoverflow.com/questions/33120389/android-should-i-maintain-a-reference-to-the-activity-inside-a-recyclerview-or

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!