实验目标:
在实验二基础上,对有recycleView的页面进行点击跳转设计。
实验内容:
1.Adapter作为复杂数据的展示的转换载体,将一系列数据显示出来,可以是列表,也可以是其他复杂形式。由于列表中每一项显示内容为三部分(产品名称、价格和配置参数),我们必须明确地告诉Android哪部分在布局文件中由哪个组件显示,并且显示的内容是什么,它借助Map来达到这个目的。然后通过RecyclerView来添加布局,同时编写一个xml文件,为RecyclerView内的元素设定xml样式,再创建适配器继承RecyclerView.Adapter,创建适配器类继承自RecyclerView.Adapter,泛型传入RecyclerView.ViewHolder类,创建内部类即RecyclerView.ViewHolder类的子类,并初始化item的控件,重写RecyclerView.Adapter类的相关方法。最后在MainActivity.java中获取RecyclerView对象,初始化数据,适配器实例化,设置LayoutManager,设置Adapter,完成功能。
List<Map<String,Object>> items=new ArrayList<Map<String,Object>>(); for(int i=0;i<products.length;i++) { Map<String,Object> item=new HashMap<String,Object>(); item.put("products", products[i]); item.put("prices", prices[i]); item.put("configurations", configurations[i]); item.put("png",R.drawable.faxian); items.add(item); } ada=new ada(items,context); LinearLayoutManager layoutManager=new LinearLayoutManager(context); layoutManager.setOrientation(RecyclerView.VERTICAL); recyclerView.setLayoutManager(layoutManager); recyclerView.setAdapter(ada);
2.通过intent实现activity之间的通信,建立监听,将点击内容传给接受的activity中,再通过判断语句选择对应的输出。
holder.itemView.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Intent intent=new Intent(context,MainActivity2.class); //startActivity(intent); intent.putExtra("xinwenye", items.get(holder.getAdapterPosition()).get("products").toString()); context.startActivity(intent); } });
接受并判断
Intent intent=getIntent(); String xinwenye=intent.getStringExtra("xinwenye"); if (xinwenye.equals("小米Note")){ textView5.setText(intent.getStringExtra("xinwenye")+"的详情页面"); } else if (xinwenye.equals("华为荣耀7")) { textView5.setText(intent.getStringExtra("xinwenye")+"的详情页面"); } else if (xinwenye.equals("魅族MX5")) { textView5.setText(intent.getStringExtra("xinwenye")+"的详情页面"); } else if (xinwenye.equals("锤子T1")) { textView5.setText(intent.getStringExtra("xinwenye")+"的详情页面"); }
结果展示