未來的幾天要來說明recyclerView的使用除了基本的使用以外還有側滑等等其他功能的使用,接下來馬上開始recyclerView的部分。
1.確認app的gradle
查看有無引入recyclerView
2.在layout中使用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">
<android.support.v7.widget.RecyclerView
android:id="@+id/card_list"
android:layout_width="match_parent"
android:layout_height="match_parent"/>
</RelativeLayout>
3.創建recyclerView item
在recyclerView中有很多物件,需要創建一個共同的物件之後生成的外觀都會依據這邊創建的來顯示。
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="horizontal"
android:padding="5dp"
android:layout_width="100dp"
android:layout_height="150dp">
<TextView
android:id="@+id/info_text"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:gravity="center"
android:background="#4C8AC2"/>
</LinearLayout>
4.創建adpater
public class MyRecyclerViewAdapter extends RecyclerView.Adapter<MyRecyclerViewAdapter.ViewHolder> {
private String[] mData;
private LayoutInflater mInflater;
MyRecyclerViewAdapter(Context context, String[] data) {
this.mInflater = LayoutInflater.from(context);
this.mData = data;
}
@Override
@NonNull
public ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
View view = mInflater.inflate(R.layout.card_item, parent, false);
return new ViewHolder(view);
}
@Override
public void onBindViewHolder(@NonNull ViewHolder holder, int position) {
holder.myTextView.setText(mData[position]);
}
@Override
public int getItemCount() {
return mData.length;
}
public class ViewHolder extends RecyclerView.ViewHolder{
TextView myTextView;
ViewHolder(View itemView) {
super(itemView);
myTextView = itemView.findViewById(R.id.info_text);
}
}
}
5.在MainActivity中創建。
這邊使用GridLayout完成網狀的版面設計,data用來放入需要顯示的資料列。
public class MainActivity extends AppCompatActivity {
MyRecyclerViewAdapter adapter;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
String[] data = {"1", "2", "3"};
RecyclerView recyclerView = findViewById(R.id.card_list);
recyclerView.setLayoutManager(new GridLayoutManager(this, 1));
adapter = new MyRecyclerViewAdapter(this, data);
recyclerView.setAdapter(adapter);
}
}
到這邊便能夠正常顯示recyclerView的內容了,未來會再延續今天的內容來完成一個簡易的翻牌小遊戲。