android – 如何在recyclerview中包含不同的意图
作者:互联网
我打算在我的项目中加入一个CardView.我已经在我的项目中包含了RecyclerView和卡片视图.问题是,我想为每张卡调用不同的活动.我已经为每张卡实现了不同的意图.但它需要我初始化数据.这是我的原始代码:
public class RecyclerAdapter extends RecyclerView.Adapter<RecyclerAdapter.ViewHolder> {
private Context context;
private String[] titles = {"Add new Research",
"View Your Research"};
private String[] details = {"Add your research files here",
"View all of your posted research"};
private int[] images = { R.drawable.add,
R.drawable.view};
class ViewHolder extends RecyclerView.ViewHolder{
public int currentItem;
public ImageView itemImage;
public TextView itemTitle;
public TextView itemDetail;
public ViewHolder(View itemView) {
super(itemView);
itemImage = (ImageView)itemView.findViewById(R.id.item_image);
itemTitle = (TextView)itemView.findViewById(R.id.item_title);
itemDetail =
(TextView)itemView.findViewById(R.id.item_detail);
itemView.setOnClickListener(new View.OnClickListener() {
@Override public void onClick(View v) {
int position = getAdapterPosition();
Intent intent = new Intent(context, Choose.class);
if(position==0){
intent = new Intent(context, AddFiles.class);
}else if(position==1){
intent = new Intent(context, ViewFiles.class);
}
context.startActivity(intent);
}
});
}
}
当我点击卡片视图时,它表示我的程序没有响应.
即使我将意图初始化为
Intent intent = null;
if(position==0){
intent = new Intent(context, AddFiles.class);
}else if(position==1){
intent = new Intent(context, ViewFiles.class);
}
context.startActivity(intent);
还有错误,我该怎么办?或者有更好的方法来做到这一点.
这是我的logcat错误.
E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.user.mcormpelo, PID: 3645
java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.String android.content.Context.getPackageName()' on a null object reference
at android.content.ComponentName.<init>(ComponentName.java:128)
at android.content.Intent.<init>(Intent.java:4449)
at com.example.user.mcormpelo.RecyclerAdapter$ViewHolder$1.onClick(RecyclerAdapter.java:46)
at android.view.View.performClick(View.java:5198)
at android.view.View$PerformClick.run(View.java:21147)
at android.os.Handler.handleCallback(Handler.java:739)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:148)
at android.app.ActivityThread.main(ActivityThread.java:5417)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)
解决方法:
您没有初始化上下文
public class RecyclerAdapter extends RecyclerView.Adapter<RecyclerAdapter.ViewHolder> {
private Context context;
public RecyclerAdapter(Context context) {
this.context = context;
}
从调用者活动传递Activity引用.
样品用法
RecyclerAdapter rcAdapter = new RecyclerAdapter(MainActivity.this);
标签:android,android-recyclerview,android-intent,onclicklistener,cardview 来源: https://codeday.me/bug/20190929/1834153.html