之前已經用過了ListView控件,雖然可以實現許多放入功能,但是其擴展性還是有一定缺陷的,比如所無法實現橫向佈局,爲此,Android中提供了一個更強大的滾動控件——RecyclerView,它可以實現ListView的功能,同時還在ListView的基礎上進行了優化。
RecyclerView基本使用
想要使用RecyclerView,首先我們應該在app的build.gradle中添加相關依賴:
dependencies {
、、、
implementation 'androidx.recyclerview:recyclerview:1.1.0'
、、、
}
之後就可以直接使用RecyclerView控件了:
<!--由於RecyclerView並不是內置在SDK中,所以必須把完整的包路徑寫下來-->
<androidx.recyclerview.widget.RecyclerView
android:id="@+id/recyclerView"
android:layout_width="match_parent"
android:layout_height="wrap_content"/>
使用RecyclerView實現ListView相同的效果:
創建主活動CardRecyclerViewActivity,設置佈局:
<?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="match_parent">
<androidx.recyclerview.widget.RecyclerView
android:id="@+id/recycler_view_card"
android:layout_width="match_parent"
android:layout_height="match_parent" />
</LinearLayout>
編寫子列表的佈局:
<?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="wrap_content"
android:orientation="horizontal">
<ImageView
android:id="@+id/card_image"
android:layout_width="150dp"
android:layout_height="150dp"
android:scaleType="fitCenter"
android:src="@mipmap/ic_launcher" />
<LinearLayout
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_weight="6"
android:layout_marginTop="3dp"
android:layout_marginLeft="5dp"
android:orientation="vertical" >
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:padding="5dp"
android:text="Name"
android:id="@+id/card_name"/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:padding="5dp"
android:text="Msg"
android:id="@+id/card_msg" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:padding="5dp"
android:text="Info"
android:id="@+id/card_info"/>
</LinearLayout>
</LinearLayout>
子列表樣式:
創建一個Card類對應我們的列表項,用來封裝數據:
public class Card {
private String name;
private int imageId;
private String msg;
private String info;
public Card(String name, int imageId,String msg,String info) {
this.name = name;
this.imageId = imageId;
this.msg=msg;
this.info=info;
}
public String getName() {
return name;
}
public int getImageId() {
return imageId;
}
public String getMsg() {
return msg;
}
public String getInfo() {
return info;
}
}
使用RecyclerView實現一個適配器,新建CardAdapter類,讓這個類繼承RecyclerView.Adapter,並將泛型置定位CardAdapter.ViewHolder。其中ViewHolder我們定義爲內部類。
繼承RecyclerView.Adapter需要實現的三個方法:
- onCreateViewHolder(ViewGroup parent, int viewType):創建ViewHolder實例,在這個方法中可以將列表佈局加載進來,之後創建一個ViewHolder實例,並把加載出來的佈局傳入到構造函數中,最後將ViewHolder實例返回。
- onBindViewHolder(ViewHolder holder, int position):用於對RecyclerView子項進行賦值,會在每個子項被滾動到屏幕內時執行,我們可以通過position獲取當前列表項對應的實例,然偶進行操作。
- getItemCount():表示RecyclerView中有多少個子項,返回數據源的長度
public class CardAdapter extends RecyclerView.Adapter<CardAdapter.ViewHolder>{
private Context context;
private List<Card> mCardList;
public CardAdapter(Context context,List<Card> cardList) {
this.context=context;
mCardList = cardList;
}
@Override
public CardAdapter.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.card_item, parent, false);
final ViewHolder holder = new ViewHolder(view);
holder.cardView.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
int position = holder.getAdapterPosition();
Card card = mCardList.get(position);
Toast.makeText(v.getContext(), card.getName()+": 奧裏給", Toast.LENGTH_SHORT).show();
}
});
holder.cardImage.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
int position = holder.getAdapterPosition();
final Card card = mCardList.get(position);
AlertDialog.Builder builder=new AlertDialog.Builder(context);
builder.setIcon(card.getImageId());
builder.setTitle(card.getName());
builder.setMessage("要拉我上船嗎?");
builder.setPositiveButton("確定", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
Toast.makeText(context,card.getName()+"加入了海賊船", Toast.LENGTH_SHORT).show();
}
});
builder.setNegativeButton("取消", null);
builder.create();
builder.show();
}
});
return holder;
}
@Override
public void onBindViewHolder(ViewHolder holder, int position) {
Card card = mCardList.get(position);
holder.cardImage.setImageResource(card.getImageId());
holder.cardName.setText(card.getName());
holder.cardMsg.setText(card.getMsg());
holder.cardInfo.setText(card.getInfo());
}
@Override
public int getItemCount() {
return mCardList.size();
}
static class ViewHolder extends RecyclerView.ViewHolder {
View cardView;
ImageView cardImage;
TextView cardName;
TextView cardMsg;
TextView cardInfo;
public ViewHolder(View view) {
super(view);
cardView = view;
cardImage = (ImageView) view.findViewById(R.id.card_image);
cardName = (TextView) view.findViewById(R.id.card_name);
cardMsg=(TextView) view.findViewById(R.id.card_msg);
cardInfo=(TextView) view.findViewById(R.id.card_info);
}
}
}
適配器準備好就可以編寫主界面了:
public class CardRecyclerViewActivity extends AppCompatActivity {
private List<Card> cardList = new ArrayList<Card>();
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_card_recycler_view);
initCards();
RecyclerView recyclerView = (RecyclerView) findViewById(R.id.recycler_view_card);
LinearLayoutManager layoutManager=new LinearLayoutManager(this);
//設置佈局管理器
recyclerView.setLayoutManager(layoutManager);
// StaggeredGridLayoutManager layoutManager = new
// StaggeredGridLayoutManager(3, StaggeredGridLayoutManager.VERTICAL);
// recyclerView.setLayoutManager(layoutManager);
//添加分割線
recyclerView.addItemDecoration(new DividerItemDecoration(
this, DividerItemDecoration.HORIZONTAL));
CardAdapter adapter = new CardAdapter(CardRecyclerViewActivity.this,cardList);
//設置adapter
recyclerView.setAdapter(adapter);
}
private void initCards() {
List<Card> list = new ArrayList<Card>();
list.add(new Card("路飛", R.mipmap.lufei,"【船長】蒙奇·D·路飛(蒙奇·D·路飛 )","1500000000¥"));
list.add(new Card("索隆", R.mipmap.suolong,"【劍士】羅羅諾亞·索隆","320000000¥"));
list.add(new Card("烏索普", R.mipmap.wusuopu,"【狙擊手】烏索普","200000000¥"));
list.add(new Card("娜美", R.mipmap.namei,"【航海士】娜美","66000000¥"));
list.add(new Card("山治", R.mipmap.shanzhi,"【廚師】香吉士","330000000¥"));
list.add(new Card("喬巴", R.mipmap.qiaoba,"【船醫】託尼託尼·喬巴","100¥"));
list.add(new Card("羅賓", R.mipmap.luobin,"【考古學家】妮可·羅賓 ","130000000¥"));
list.add(new Card("弗蘭奇", R.mipmap.fulanqi,"【船匠】弗蘭奇","94000000¥"));
list.add(new Card("布魯克", R.mipmap.buluke,"【音樂家】布魯克","83000000¥"));
list.add(new Card("香克斯", R.mipmap.xiangkesi,"【四皇】香克斯","4000000000¥"));
for(int i=0;i<60;i++){
cardList.add(list.get((int)(Math.random()*10)));
}
}
}
運行結果:
實現不同樣式的佈局
修改子列表項的佈局:card_item.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="vertical">
<RelativeLayout
android:layout_width="150dp"
android:layout_height="150dp">
<ImageView
android:id="@+id/card_image"
android:layout_width="150dp"
android:layout_height="150dp"
android:scaleType="fitCenter"
android:src="@mipmap/ic_launcher" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Name"
android:id="@+id/card_name"/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:text="Info"
android:id="@+id/card_info"/>
</RelativeLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="3dp"
android:layout_marginLeft="5dp"
android:orientation="vertical" >
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:padding="5dp"
android:textSize="15dp"
android:text="Msg"
android:id="@+id/card_msg" />
</LinearLayout>
</LinearLayout>
修改主活動的代碼:
//LinearLayoutManager layoutManager=new LinearLayoutManager(this);
//recyclerView.setLayoutManager(layoutManager);
//橫向的效果
LinearLayoutManager layoutManager=new LinearLayoutManager(this);
layoutManager.setOrientation(LinearLayoutManager.HORIZONTAL);
recyclerView.setLayoutManager(layoutManager);
//網格佈局
GridLayoutManager gridLayoutManager = new GridLayoutManager( this,3);
recyclerView.setLayoutManager(gridLayoutManager);
//流式佈局
StaggeredGridLayoutManager layoutManager = new
StaggeredGridLayoutManager(3, StaggeredGridLayoutManager.VERTICAL);
recyclerView.setLayoutManager(layoutManager);
橫向佈局:
網格佈局:
流式佈局: