這次要介紹的RecyclerView可以說是ListView的改良版,相較於ListView,它較ListView更有彈性、容易客製化,且具官方說法,效能方面有很大的提升,在有了ListView的基礎後,設計RecyclerView也會理解較快。
首先,在gradle加入以下library dependency 後按下Sync Now
implementation 'com.android.support:appcompat-v7:23.4.0'
implementation 'com.android.support:design:23.4.0'
完成以後就可以開始RecyclerView設計了
在XML插入RecyclerView元件
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent" >
<androidx.recyclerview.widget.RecyclerView
android:id="@+id/recyclerView"
android:layout_width="match_parent"
android:layout_height="match_parent" />
</RelativeLayout>
接著設定RecyclerView中每一行要顯示的元件,開一個新的XML取名為list_content.xml,內容為下
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="60dp"
android:orientation="horizontal">
<TextView
android:id="@+id/fileTitle"
android:text="TextView"
android:layout_width="match_parent"
android:layout_height="60dp"
android:layout_marginLeft="5dp"
android:gravity="center_vertical|left" ></TextView>
</LinearLayout>
接下來開始定義Adapter,在右邊專案資料夾右鍵 -> New -> Java Class,創建一個Class,範例中命名為MyAdapter並繼承RecyclerView.Adapter<MyAdapter.ViewHolder>
public class MyAdapter extends RecyclerView.Adapter<MyAdapter.ViewHolder> {
ArrayList<String> titleList;
//帶入ArrayList作為資料
public MyAdapter(ArrayList<String> titleList) {
this.titleList = titleList;
}
@Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext())
.inflate(R.layout.list_content, parent, false);
return new ViewHolder(view);
}
@Override
public void onBindViewHolder(ViewHolder holder, int position) {
holder.fileTitle.setText(titleList.get(position));
}
//RecyclerView長度
@Override
public int getItemCount() {
return titleList.size();
}
class ViewHolder extends RecyclerView.ViewHolder {
public ImageView img;
public TextView fileTitle;
public ViewHolder(View holder) {
super(holder);
//綁定元件ID
fileTitle = (TextView) holder.findViewById(R.id.fileTitle);
}
}
}
設定完Adapter就可開始撰寫MainActivity
public class MainActivity extends AppCompatActivity {
MyAdapter adapter;
RecyclerView recyclerView;
ArrayList<String> titleList = new ArrayList();
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
recyclerView = findViewById(R.id.recyclerView);
//給titleList資料
for(int i = 0;i<10;i++){
titleList.add(String.valueOf(i));
}
recyclerView.setLayoutManager(new LinearLayoutManager(this));
recyclerView.addItemDecoration(new DividerItemDecoration(this,
DividerItemDecoration.VERTICAL));
adapter = new MyAdapter(titleList);
recyclerView.setAdapter(adapter);
}
}