RecyclerView.Adapter的上下文

Aug*_*ust 1 android android-context android-adapter

我想添加ProgressDialog一个适配器。AFAIK,.this用于活动和getActivity.getApplicationContext()片段。那适配器呢?可能吗?

Unable to add window -- token null is not valid; is your activity running?使用时出现错误mContext.getApplicationContext()

编辑:

在一个片段中,我将卡片显示为

allGroupsView = (RecyclerView) rootView.findViewById(R.id.allGroupsView);
adapterGroup = new AdapterGroup(getActivity().getApplicationContext(), results);
allGroupsView.setAdapter(adapterGroup);
allGroupsView.setLayoutManager(new LinearLayoutManager(getActivity().getApplicationContext()));
Run Code Online (Sandbox Code Playgroud)

在班上 AdapterGroup

public class AdapterGroup extends RecyclerView.Adapter<RecyclerView.ViewHolder> {

private Context mContext;
private LayoutInflater inflater;
List<DataGroup> data= Collections.emptyList();
DataGroup current;

public AdapterGroup(Context context, List<DataGroup> results) {
    this.mContext = context;
    inflater = LayoutInflater.from(mContext);
    this.data = results;
}

// Inflate the layout when viewholder created
@Override
public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
    View view = inflater.inflate(R.layout.card_view_row, parent, false);
    final MyHolder holder = new MyHolder(view);

    view.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            Log.d("debug", String.valueOf(holder.getAdapterPosition()));
            getDetails(Config.GET_GROUP_DETAILS_URL, data.get(holder.getAdapterPosition()).groupName, data.get(holder.getAdapterPosition()).description);
        }
    });

    return holder;
}

private void getDetails(String url, String groupName, String description) {

    groupName = groupName.replace(" ", "%20");
    description = description.replace(" ", "%20");

    final String finalGroupName = groupName;
    final String finalDescription = description;

    class GetDetails extends AsyncTask<String, Void, String> {
        ProgressDialog loading;

        @Override
        protected void onPreExecute() {
            super.onPreExecute();
            loading = ProgressDialog.show(mContext.getApplicationContext(), null, "Please wait", true, true);
            loading.setCancelable(false);
        } // more code down from here
Run Code Online (Sandbox Code Playgroud)

Chr*_*hua 5

我看过很多代码,人们在其中始终引用Adapter中的Context。但在RecyclerView.Adapter,该ItemView控件(你已经从膨胀的观点onCreateViewHolder)是从ViewHolder访问。在大多数情况下,无论如何,您都应该处理viewHolder。因此,请使用viewholder.itemView.getContext();。您甚至可以在Viewholder getContext()中公开一个方法。

public Context getContext() {return itemView.getContext();}
Run Code Online (Sandbox Code Playgroud)