iT邦幫忙

2022 iThome 鐵人賽

DAY 17
0
Mobile Development

Android studio 30天新手筆記系列 第 17

Day17-Android新手筆記-RecyclerView元件基本介紹

  • 分享至 

  • xImage
  •  

RecyclerView的UI設計可以很豐富,在客製化的時候彈性頗大。今天先介紹基礎的RecyclerView使用,相較先前介紹的ListView來的稍加複雜。但整體使用感受上,我覺得比ListView來的好上許多。

/images/emoticon/emoticon31.gif

在開始介紹前,先來看看今天的小目標:

基本流程如下:
1 .建立Item檔案
2 .實作RecyclerViewAdapter
3 .主頁面RecyclerView元件設定

首先先建立一個Item檔案,Item檔提供RecyclerView中的每行樣式

<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="wrap_content">

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="50dp"
        android:orientation="horizontal"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent">

        <TextView
            android:id="@+id/textView_number"
            android:layout_width="wrap_content"
            android:layout_height="match_parent"
            android:layout_weight="1"
            android:gravity="center"
            android:text="TextView"
            android:textSize="20sp" />

        <TextView
            android:id="@+id/textView_name"
            android:layout_width="wrap_content"
            android:layout_height="match_parent"
            android:layout_weight="1"
            android:gravity="center"
            android:text="TextView"
            android:textSize="20sp" />

        <TextView
            android:id="@+id/textView_phone"
            android:layout_width="wrap_content"
            android:layout_height="match_parent"
            android:layout_weight="1"
            android:gravity="center"
            android:text="TextView"
            android:textSize="20sp" />
    </LinearLayout>
</androidx.constraintlayout.widget.ConstraintLayout>

接下來於activity_main.xml中加入RecyclerView元件,完整XML如下:

<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity">

    <androidx.recyclerview.widget.RecyclerView
        android:id="@+id/recyclerView"
        android:layout_width="0dp"
        android:layout_height="0dp"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintHorizontal_bias="0.0"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent" />


</androidx.constraintlayout.widget.ConstraintLayout>

XML設定好後,建立一個StudentData.java用來放入要顯示的資料格式:

public class StudentData {
    int number;
    String phone;
    String name;

    public StudentData(int number,String phone,String name){
        this.number = number;
        this.phone = phone;
        this.name = name;
    }

    public int getNumber() {
        return number;
    }

    public void setNumber(int number) {
        this.number = number;
    }

    public String getPhone() {
        return phone;
    }

    public void setPhone(String phone) {
        this.phone = phone;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }
}

接下來建立RecyclerViewAdapter.java,程式碼如下:

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

    List<StudentData> studentDataList = new ArrayList<>();
    Context context;
    public RecyclerViewAdapter(Context context){
        this.context = context;
    }

    public class ViewHolder extends RecyclerView.ViewHolder{
        TextView textView_number,textView_name,textView_phone;
        public ViewHolder(@NonNull View itemView) {
            super(itemView);
            textView_name = itemView.findViewById(R.id.textView_name);
            textView_number = itemView.findViewById(R.id.textView_number);
            textView_phone = itemView.findViewById(R.id.textView_phone);
        }

        void setShowValue(int position){
        //設定顯示資料
       textView_number.setText(String.format("%02d",studentDataList.get(position).getNumber()));
            textView_name.setText(studentDataList.get(position).getName());
            textView_phone.setText(studentDataList.get(position).getPhone());
        }

        void setItemViewOnclick(int position){
            //itemView點擊事件
            itemView.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    Toast.makeText(v.getContext(),"您選擇的是第 " + ( position + 1 ) + " 項", Toast.LENGTH_SHORT).show();
                }
            });
        }

    }

    @NonNull
    @Override
    public ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        //加載Item布局
        View view = LayoutInflater.from(parent.getContext())
                .inflate(R.layout.item, parent,false);
        return new ViewHolder(view);
    }
    @Override
    public void onBindViewHolder(@NonNull ViewHolder holder, int position) {
        //設定顯示資料
        holder.setShowValue(position);
        //設定ItemView的點擊事件
        holder.setItemViewOnclick(position);
    }

    @Override
    public int getItemCount() {
        //設定顯示數量
        return studentDataList.size();
    }

    //傳入MainActivity中的studentDataList
    public void setStudentData(List<StudentData> studentDataList){
        this.studentDataList = studentDataList;
        notifyDataSetChanged();
    }
}

Adapter設定好之後,回到MainActivity中,設定RecyclerView元件:

public class MainActivity extends AppCompatActivity {
    RecyclerView recyclerView;
    RecyclerViewAdapter recyclerViewAdapter;
    StudentData student;
    List<StudentData> studentDataList = new ArrayList<>();
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        //建立假資料
        for(int i = 0;i<30;i++){
            student =  new StudentData(i+1,
                                "09"+String.format("%08d",i+1),
                                "XXX");
            studentDataList.add(student);
        }
        
        recyclerView = findViewById(R.id.recyclerView);
        //設置布局管理器
        recyclerView.setLayoutManager(new LinearLayoutManager(this));
        //設置RecyclerViewAdapter與傳入要顯示的資料
        recyclerViewAdapter = new RecyclerViewAdapter(this);
        recyclerViewAdapter.setStudentData(studentDataList);
        recyclerView.setAdapter(recyclerViewAdapter);
        //添加底線樣式
        recyclerView.addItemDecoration(new DividerItemDecoration(this, DividerItemDecoration.VERTICAL));
    }
}

/images/emoticon/emoticon41.gif


上一篇
Day16-Android新手筆記-SharedPreferences
下一篇
Day18-Android新手筆記-RecyclerView滑動刪除與上下拖曳
系列文
Android studio 30天新手筆記30
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言