使用recycleview添加微信消息列表
1. 将支持库添加到 dependencies 部分。
dependencies {
implementation 'com.android.support:recyclerview-v7:28.0.0'
}
2. 将 RecyclerView 添加到布局中
2.1 将微信fragment的布局改为recycleView布局
现在需要将 RecyclerView 添加到上次的微信fragment对应的布局文件中。使用 RecyclerView 作为整个布局的唯一视图:
<?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"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:orientation="vertical">
<!-- <TextView-->
<!-- android:layout_width="match_parent"-->
<!-- android:layout_height="match_parent"-->
<!-- android:gravity="center"-->
<!-- android:text="这是微信聊天界面"-->
<!-- android:textSize="30sp"-->
<!-- android:textStyle="bold"/>-->
<androidx.recyclerview.widget.RecyclerView
android:id="@+id/weixin_recycler_view"
android:layout_width="match_parent"
app:layout_constraintTop_toTopOf="parent"
android:layout_height="wrap_content"/>
</LinearLayout>
在布局中添加了 weixinRecycleViewAdapter 微件之后,需要获取对象句柄,将其连接到布局管理器,并为要显示的数据附加适配器。
代码大致结构如下:
package com.example.myapplication.fragment;
import android.os.Bundle;
import android.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import com.example.myapplication.R;
import com.example.myapplication.adapter.weixinRecycleViewAdapter;
import com.example.myapplication.entity.weixin;
import java.util.ArrayList;
public class weixinFragment extends Fragment {
private View view;
private RecyclerView recyclerView;
private RecyclerView.Adapter mAdapter;
private RecyclerView.LayoutManager layoutManager;
public weixinFragment() {
// Required empty public constructor
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
view=inflater.inflate(R.layout.table01, container, false);
initRecyclerView();
return view;
}
private void initRecyclerView() {
recyclerView = (RecyclerView) view.findViewById(R.id.weixin_recycler_view);
recyclerView.setHasFixedSize(true);
layoutManager = new LinearLayoutManager(getActivity()