用RecyclerView实现根据位置不同显示不同界面
在原来的基础上将LinearAdapter.java进行修改:
1 public class LinearAdapter extends RecyclerView.Adapter{ 2 private Context mcontext; 3 private OnItemClickListener mlistener; 4 public LinearAdapter(Context context,OnItemClickListener listener){ 5 this.mcontext=context; 6 this.mlistener=listener; 7 } 8 @NonNull 9 @Override 10 public RecyclerView.ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) { 11 if(viewType==2){ 12 return new LinearViewHolder(LayoutInflater.from(mcontext).inflate(R.layout.layout_linear_item,parent,false)); 13 }else{ 14 return new LinearViewHolder2(LayoutInflater.from(mcontext).inflate(R.layout.layout_linear_item_2,parent,false)); 15 } 16 } 17 18 @Override 19 public void onBindViewHolder(@NonNull RecyclerView.ViewHolder holder,int position) { 20 if(getItemViewType(position)==2){ 21 ((LinearViewHolder)holder).textView.setText("大家好,我又来了hiahia"); 22 }else{ 23 ((LinearViewHolder2)holder).textView.setText("新年快乐!!"); 24 } 25 holder.itemView.setOnClickListener(new View.OnClickListener() { 26 @Override 27 public void onClick(View view) { 28 //Toast.makeText(mcontext, "click...", Toast.LENGTH_SHORT).show();//第一种方法,如果加position的话就会标红,所以没加,具体原因还不知道 29 mlistener.onClick(position);//第二种方法,反正点击事件没起作用,还是算了吧不弄了 30 } 31 });//增加点击事件,这是第一种方法 32 }//这里原来是RecyclerView.ViewHolder,建立完LinearViewHolder class后要把它改成LinearAdapter.LinearViewHolder就可以了 33 34 public int getItemViewType(int position){ 35 if(position%2==0){ 36 return 2;//位置是偶数,返回2 37 }else { 38 return 1;//否则返回1 39 } 40 } 41 42 @Override 43 public int getItemCount() { 44 return 20; 45 }//设置有多少行 46 47 class LinearViewHolder extends RecyclerView.ViewHolder { 48 private TextView textView; 49 public LinearViewHolder(@NonNull View itemView) { 50 super(itemView); 51 textView=itemView.findViewById(R.id.tv_rtitle); 52 } 53 } 54 55 class LinearViewHolder2 extends RecyclerView.ViewHolder { 56 private TextView textView; 57 private ImageView imageView; 58 public LinearViewHolder2(@NonNull View itemView) { 59 super(itemView); 60 textView=itemView.findViewById(R.id.tv_rtitle); 61 imageView=itemView.findViewById(R.id.iv_jiqiren); 62 } 63 } 64 65 public interface OnItemClickListener{ 66 void onClick(int pos); 67 }//点击事件的第二种方法,建立接口 68 }
然后创建另一个界面layout_linear_item_2.xml文件:
1 <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" 2 android:layout_width="match_parent" 3 android:layout_height="wrap_content" 4 android:orientation="vertical" 5 android:background="@color/white" 6 android:gravity="center"> 7 8 <TextView 9 android:id="@+id/tv_rtitle" 10 android:layout_width="match_parent" 11 android:layout_height="50dp" 12 android:gravity="center" 13 android:textColor="@color/black" 14 android:textSize="20sp"/> 15 16 <ImageView 17 android:id="@+id/iv_jiqiren" 18 android:layout_width="wrap_content" 19 android:layout_height="wrap_content" 20 android:src="@drawable/jiqiren"/> 21 LinearLayout>
最终效果图: