Android:我应该在 recyclerview 中保留对 activity 的引用还是有其他方法?

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

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

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

您可以在应用程序中有一个上下文 class 并且可以有一个静态方法来获取该上下文。

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

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

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

为了完整起见,我 post 我通常采用的解决方案也保留了对 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
    }
}