我有一个RecyclerView加载我的String数组的内容工作正常,但我想根据他们按下的视图打开一个新的活动.
我所做的是创建一个名为类的数组,如下所示:
<array name="classes"> <item>ClassOne</item> <item>ClassTwo</item> <item>ClassThree</item> <item>ClassFour</item> </array>
它们存储在一个数组中,并传递给我的MainActivityList适配器:
String[] classes = resource.getStringArray(R.array.classes); MainActivityList adapter = new MainActivityList(titles,content,images,classes); recyclerView.setAdapter(adapter);
我已经设法将OnClickListener添加到ViewHolder并输出为每个视图分配给日志的类,但是我无法弄清楚或开始工作,如何启动另一个活动.
例如,类名将类似于ClassOne.class
public class MainActivityList extends RecyclerView.Adapter<MainActivityList.ViewHolder> { private String[] mTitles; private String[] mContent; private String[] mClasses; private TypedArray mImages; private Context context; public MainActivityList(String[] titles,String[] content,TypedArray images,String[] classes) { this.mTitles = titles; this.mContent = content; this.mImages = images; this.mClasses = classes; } @Override public ViewHolder onCreateViewHolder(ViewGroup viewGroup,int i) { final View v = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.activity_main_card,viewGroup,false); ViewHolder vh = new ViewHolder(v); v.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { ViewHolder vh = (ViewHolder)v.getTag(); Log.v("DEBUG","Clicked" + vh.classes); } }); return vh; } public void onBindViewHolder(ViewHolder holder,int position) { holder.titleView.setText(mTitles[position]); holder.contentView.setText(mContent[position]); holder.imageView.setImageDrawable(mImages.getDrawable(position)); holder.classes = mClasses[position]; } public class ViewHolder extends RecyclerView.ViewHolder { public TextView titleView; public TextView contentView; public ImageView imageView; public String classes; public ViewHolder(View v) { super(v); titleView = (TextView) v.findViewById(R.id.card_title); contentView = (TextView) v.findViewById(R.id.card_content); imageView = (ImageView)v.findViewById(R.id.card_image); v.setTag(this); } } @Override public int getItemCount() { return mTitles.length; } }
解决方法
我也在寻找解决方案,我找到了这篇文章:
http://venomvendor.blogspot.sg/2014/07/setting-onitemclicklistener-for-recycler-view.html
http://venomvendor.blogspot.sg/2014/07/setting-onitemclicklistener-for-recycler-view.html
通过使用OnItemClickListener接口,您应该能够在活动中调用startActivity.
adapter.SetOnItemClickListener(new OnItemClickListener() { @Override public void onItemClick(View v,int position) { // This is in an Activity so should be able to start new activity,etc. } });