我想在适配器中添加 ProgressDialog
。 AFAIK,.this
用于 Activity ,getActivity.getApplicationContext()
用于 fragment 。适配器呢?可能吗?
我收到错误 无法添加窗口 -- 标记 null 无效;你的 Activity 在运行吗?
当我使用 mContext.getApplicationContext()
时。
编辑:
在 fragment 中,我通过以下方式显示卡片
allGroupsView = (RecyclerView) rootView.findViewById(R.id.allGroupsView);
adapterGroup = new AdapterGroup(getActivity().getApplicationContext(), results);
allGroupsView.setAdapter(adapterGroup);
allGroupsView.setLayoutManager(new LinearLayoutManager(getActivity().getApplicationContext()));
在类 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
最佳答案
我见过很多代码,人们在这些代码中不断引用适配器中的上下文。但是在 RecyclerView.Adapter 中,itemView(您已经从 onCreateViewHolder 膨胀的 View )可以从您的 ViewHolder 访问。在大多数情况下,您无论如何都应该处理 viewHolder。所以,使用 viewholder.itemView.getContext();。您甚至可以在 viewholder getContext() 中公开一个方法。
public Context getContext() {return itemView.getContext();}
关于android - RecyclerView.Adapter 的上下文,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40101566/