Tak*_*r07 1 java android dialog android-alertdialog android-activity
我正在使用RecyclerView,并且只要长按RecyclerView中的项目,就想打开AlertDialog.
在RecyclerView的ViewHolder中,我实现了clicklistener
@Override
public boolean onLongClick(View v) {
//Open Alert dialog to delete item
AlertDialog.Builder alert = new AlertDialog.Builder(context);
...
}
Run Code Online (Sandbox Code Playgroud)
我可以在这里阅读:http://goo.gl/Kd1c7i一个需要通过"MyActivity.this"到AlertDialog.Builder构造函数,但由于ViewHolder是RecyclerView适配器的静态部分,我不能引用"MyActivity.这个".因此我仍然得到错误:
android.view.WindowManager$BadTokenException: Unable to add window -- token null is not for an application
Run Code Online (Sandbox Code Playgroud)
那么如何从不扩展Activity的类创建AlertDialog?
@Edit:更多代码以获取更多信息:
这是我的RecyclerView Adapter构造函数:
RecyclerViewCourseAdapter(ArrayList<Course> courses, Context context) {
this.context = context;
if (courses == null) {
throw new IllegalArgumentException("courses ArrayList must not be null");
}
mCourseArrayList = courses;
}
Run Code Online (Sandbox Code Playgroud)
我将给定的上下文存储为Adapter类中的private:
private Context context;
Run Code Online (Sandbox Code Playgroud)
这是我的ViewHolder:
public static class ViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener,View.OnLongClickListener {
//Initialize views in Viewholder
TextView mTextViewFirst;
TextView mTextViewSecond;
ImageView mImageView;
TextView mEndPercentageTextView;
//Context to refer to app context (for intent, dialog etc)
Context context;
//Adapter to notifiy data set changed
RecyclerViewCourseAdapter mCourseAdapter;
public ViewHolder(View itemView, Context context, RecyclerViewCourseAdapter mCourseAdapter) {
super(itemView);
this.context = context;
this.mCourseAdapter = mCourseAdapter;
itemView.setOnClickListener(this);
itemView.setOnLongClickListener(this);
mTextViewFirst = (TextView) itemView.findViewById(R.id.course_firstLine);
mTextViewSecond = (TextView) itemView.findViewById(R.id.course_secondLine);
mImageView = (ImageView) itemView.findViewById(R.id.icon);
mEndPercentageTextView = (TextView) itemView.findViewById(R.id.end_percentage_textview);
}
Run Code Online (Sandbox Code Playgroud)
这就是我创建视图的方式:
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
//Inflate layout
View itemView = LayoutInflater.from(parent.getContext()).inflate(R.layout.list_item_course, parent, false);
ViewHolder vh = new ViewHolder(itemView, context, this);
return vh;
}
Run Code Online (Sandbox Code Playgroud)
所以我使用适配器中存储的上下文创建我的ViewHolder.
如果事情仍unlcear,这里是我的全班同学: https://github.com/Tak3r07/UniHelper/blob/master/app/src/main/java/com/tak3r07/CourseStatistics/RecyclerViewCourseAdapter.java
每个人View
都有一个背景,改变:
AlertDialog.Builder alert = new AlertDialog.Builder(context);
Run Code Online (Sandbox Code Playgroud)
至
AlertDialog.Builder alert = new AlertDialog.Builder(v.getContext());
Run Code Online (Sandbox Code Playgroud)
有关详细信息,请参阅文档:
http://developer.android.com/reference/android/view/View.html#getContext()