Android:我应该维护对recyclerview内部活动的引用,还是有另一种方式?

我需要在onBindViewHolder中使用上下文方法(标准示例可能像getString或getColor一样常见)。 到目前为止,我已经将上下文传递给了recyclerview的构造函数,并在变量中维护了一个引用,但在我看来,这似乎是不好的做法。 有没有办法从recyclelerview内部动态获取上下文而不将其存储为变量?

public SomeRecyclerViewClass(Activity activity) { this.parentActivity = activity; } 

我看不出在构造函数中传递Context并将其存储在字段中的任何缺点。 无论如何,您可以通过这种方式访问​​它:

 public class MyAdapter extends RecyclerView.Adapter { @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 } } 

为了完整LayoutInflater ,我发布了我通常采用的解决方案,它也保留了对LayoutInflater的引用:

 public class MyAdapter extends RecyclerView.Adapter { 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 } } 

您可以在应用程序类中使用上下文,并且可以使用静态方法来获取该上下文。

 public class MyApp extends android.app.Application { private static MyApp instance; public MyApp() { instance = this; } public static Context getContext() { return instance; }} 

你可以这样做:

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