1. 程式人生 > >Android Studio RecyclerView用法

Android Studio RecyclerView用法

首先建立一個佈局 裡面放一個文字

 <TextView
        android:id="@+id/textView"
        android:layout_width="60dp"
        android:layout_height="20dp"
        android:text="TextView"
       />

在主活動中加入RecyclerView 

 <android.support.v7.widget.RecyclerView
        android:id="@+id/recyclerView"
android:layout_width="match_parent" android:layout_height="match_parent" />

新增一個空的活動做介面卡

package com.example.myapplication;

import android.support.annotation.NonNull;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import java.util.List;

public class Main2Activity extends RecyclerView.Adapter<Main2Activity.ViewHolder> {

private List<String> list;

static class ViewHolder extends RecyclerView.ViewHolder
{
TextView name;
View Vie;
public ViewHolder(View v)
{
super(v);
Vie=v;
name=v.findViewById(R.id.textView);
}

}

public Main2Activity(List<String> lists)
{
list=lists;
}

@NonNull
@Override
public ViewHolder onCreateViewHolder(@NonNull ViewGroup viewGroup, int i) {
View view=LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.file,viewGroup,false) ;//載入要自定義的佈局
final ViewHolder holder=new ViewHolder(view);
holder.Vie.setOnClickListener(new View.OnClickListener(){//註冊單擊事件
@Override
public void onClick(View v) {

String string= list.get( holder.getAdapterPosition());

Toast.makeText(v.getContext(), string, Toast.LENGTH_SHORT).show();
}
});
return holder;
}

@Override
public void onBindViewHolder(@NonNull ViewHolder viewHolder, int i) {
String f=list.get(i);//獲取當前數值
viewHolder.name.setText(f);//賦值

}

@Override
public int getItemCount() {
return list.size();
}

}

初始化列表資料

 private  List<String> lit=new ArrayList<>();
    private  void  inte()
    {
        lit.add("3");
        lit.add("2");
        lit.add("3");
    }
       inte();
       RecyclerView recyclerView=findViewById(R.id.recyclerView);//獲取控制元件值
        LinearLayoutManager layoutManager=new
LinearLayoutManager(this);//線性佈局 recyclerView.setLayoutManager(layoutManager); Main2Activity ad=new Main2Activity(lit); recyclerView.setAdapter(ad);