ListView和RecyclerView

作者: uniapp | 来源:发表于2017-06-12 16:17 被阅读136次

    做iOS开发时,明白UITableView和UICollectionView的常用性和重要性,它们都是UIScrollView的子类,因为加入cell的重用机制,使得手机能够流畅的显示超过屏幕的内容.同样Android开发中,相对应的就是ListView和RecyclerView.RecyclerView通过设置layoutManager的orientation属性,实现横向滑动,性能也优于ListView.下面通过对同一个Demo的实现,来对比学习和掌握二者.
    先看一下最终效果,其中点击SEND按钮,将发送消息并滚动到最后.

    RecyclerView

    首先使用ListView,在layout中创建每一条消息的布局item.xml,代码如下:

    <?xml version="1.0" encoding="utf-8"?>
    <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
        android:orientation="vertical" android:layout_width="match_parent"
        android:layout_height="wrap_content">
    
        <LinearLayout
            android:id="@+id/layout_left"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_marginRight="20dp"
            android:layout_gravity="left|center_vertical"
            android:orientation="horizontal">
            <ImageView
                android:layout_width="50dp"
                android:layout_height="50dp"
                android:layout_gravity="left|center_vertical"
                android:id="@+id/imageView_itemLeft"/>
            <TextView
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:id="@+id/textView_itemLeft"
                android:gravity="left|center_vertical"/>
        </LinearLayout>
    
        <LinearLayout
            android:id="@+id/layout_right"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:orientation="horizontal"
            android:layout_marginLeft="20dp"
            android:gravity="right|center_vertical">
            <TextView
                android:layout_width="0dp"
                android:layout_weight="1"
                android:layout_height="wrap_content"
                android:gravity="right|center_vertical"
                android:id="@+id/textView_itemRight"/>
            <ImageView
                android:layout_width="50dp"
                android:layout_height="50dp"
                android:id="@+id/imageView_itemRight" />
        </LinearLayout>
    
    </LinearLayout>
    

    使用LinearLayout布局,创建layout_left和layout_right分别用于显示接受的消息和发送的消息.
    在activity_main.xml中,使用LinearLayout布局,添加ListView控件和新的LinearLayout布局,添加EidtText和Button用于输入消息和发送消息.

    <?xml version="1.0" encoding="utf-8"?>
    <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
        android:orientation="vertical"
        android:layout_width="match_parent"
        android:layout_height="match_parent">
    
        <ListView
            android:id="@+id/listView_msg"
            android:layout_width="match_parent"
            android:layout_height="400dp"
            android:background="#ffffff"
            android:layout_weight="1">
    
        </ListView>
    
        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="50dp"
            android:orientation="horizontal"
            android:layout_gravity="bottom">
    
            <EditText
                android:layout_width="wrap_content"
                android:layout_height="40dp"
                android:layout_marginBottom="10dp"
                android:layout_weight="1"
                android:id="@+id/editText_msg"
                android:hint="write your title here"/>
            <Button
                android:id="@+id/send_button"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_gravity="center"
                android:text="Add"/>
    
        </LinearLayout>
    </LinearLayout>
    

    在java文件夹下的文件包中,增加存储消息的Message类.type表示消息的类型,用于控制item中layout的显示.content表示消息的具体内容.

    public class Message {
        public static final int TYPE_RECEIVED = 1;
        public static final int TYPE_SENT = 0;
    
        private String content;
        private int type;
    
        public Message(int type, String content) {
            this.type = type;
            this.content = content;
        }
    
        public int getType() {
            return this.type;
        }
    
        public String getContent() {
            return this.content;
        }
    }
    

    添加继承自ArrayAdapter类的MsgAdapter.重写构造方法

    public ArrayAdapter(@NonNull Context context, @LayoutRes int resource,
    @NonNull List<T> objects)

    记录resouce用于getView中View的创建.
    已经创建好的item.xml在getView方法中应用,创建用于显示消息的View.

    public class MsgAdapter extends ArrayAdapter<Message> {
    
        private int resourceId;
        public MsgAdapter(Context context, int resouceId, List<Message> messages) {
            super(context, resouceId, messages);
    
            this.resourceId = resouceId;
        }
    
        @NonNull
        @Override
        public View getView(int position, @Nullable View convertView, @NonNull ViewGroup parent) {
    
            View view = LayoutInflater.from(parent.getContext()).inflate(resourceId, parent, false);
            LinearLayout leftLayout = (LinearLayout)view.findViewById(R.id.layout_left);
            LinearLayout rightLayout = (LinearLayout)view.findViewById(R.id.layout_right);
            Message msg = getItem(position);
            ImageView imageView;
            TextView textView;
            if (msg.getType() == Message.TYPE_RECEIVED) {
                leftLayout.setVisibility(View.VISIBLE);
                rightLayout.setVisibility(View.GONE);
                imageView = (ImageView)view.findViewById(R.id.imageView_itemLeft);
                textView = (TextView)view.findViewById(R.id.textView_itemLeft);
                imageView.setImageResource(R.drawable.left);
            }else {
                leftLayout.setVisibility(View.GONE);
                rightLayout.setVisibility(View.VISIBLE);
                imageView = (ImageView)view.findViewById(R.id.imageView_itemRight);
                textView = (TextView)view.findViewById(R.id.textView_itemRight);
                imageView.setImageResource(R.drawable.right);
            }
    
            textView.setText(msg.getContent());
            return view;
        }
    }
    

    最后在MainActivity中渲染ListView.

    public class MainActivity extends AppCompatActivity {
    
        private List<Message> msgList = new ArrayList<Message>();
        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_main);
    
            initMessage();
            final MsgAdapter msgAdapter = new MsgAdapter(this, R.layout.item, msgList);
            final ListView listView = (ListView)findViewById(R.id.listView_msg);
            listView.setAdapter(msgAdapter);
    
            final EditText editText = (EditText) findViewById(R.id.editText_msg);
            Button btn = (Button) findViewById(R.id.send_button);
            btn.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    String content = editText.getText().toString();
                    if (!"".equals(content)) {
                        Message msg = new Message(0, content);
                        msgList.add(msg);
                        msgAdapter.notifyDataSetChanged();
                        listView.smoothScrollToPosition(listView.getCount()-1);//移动到尾部
                        editText.setText("");
                    }
    
                }
            });
        }
    
        private void initMessage() {
            for (int i = 0; i < 3; i++) {
                Message msg0 = new Message(1, "How are you?");
                Message msg1 = new Message(0, "I am fine, thank you. And you?");
                Message msg2 = new Message(1, "I am fine, too");
                msgList.add(msg0);
                msgList.add(msg1);
                msgList.add(msg2);
            }
        }
    }
    

    下面用RecyclerView实现上述效果.
    首先App的build.gradle文件中,添加RecyclerView的支持包(版本号和Android Studio保持一致).

    compile 'com.android.support:recyclerview-v7:25.3.1'

    在activity_main.xml文件中使用RecyclerView,替换ListView.

    <?xml version="1.0" encoding="utf-8"?>
    <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
        android:orientation="vertical"
        android:layout_height="match_parent"
        android:layout_width="match_parent">
    
        <android.support.v7.widget.RecyclerView
            android:id="@+id/recycle_view"
            android:layout_width="match_parent"
            android:layout_weight="1"
            android:layout_height="100dp" />
        <!--android:background="#ffddff"-->
        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="50dp">
            <!--android:background="#00ffff"-->
            <EditText
                android:id="@+id/input_text"
                android:layout_width="wrap_content"
                android:layout_height="40dp"
                android:layout_marginBottom="10dp"
                android:layout_marginRight="10dp"
                android:layout_weight="1"
                android:hint="yourMsg"/>
            <Button
                android:id="@+id/send_button"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text="Send"/>
        </LinearLayout>
    
    
    </LinearLayout>
    

    其中新增的item.xml和Message文件不变.新增继承至RecyclerView.Adapter的类MsgAdapter.首先创建ViewHolder,在创建方法中,记录需要具体设置的控件属性.在onCreateViewHolder方法中创建ViewHolder,在onBindViewHolder方法中为控件负值,在getItemCount方法中,设置item的个数.

    public class MsgAdapter extends RecyclerView.Adapter<MsgAdapter.ViewHolder> {
    
        private List<Msg> msgList;
        static class ViewHolder extends RecyclerView.ViewHolder {
    
            LinearLayout left_layout;
            ImageView left_imageView;
            TextView left_textView;
    
            LinearLayout right_layout;
            ImageView right_imageView;
            TextView right_textView;
            public ViewHolder(View view) {
                super(view);
                left_layout = (LinearLayout)view.findViewById(R.id.left_layout);
                left_imageView = (ImageView)view.findViewById(R.id.left_image);
                left_textView = (TextView)view.findViewById(R.id.left_text);
    
                right_layout = (LinearLayout)view.findViewById(R.id.right_layout);
                right_imageView = (ImageView)view.findViewById(R.id.right_image);
                right_textView = (TextView)view.findViewById(R.id.right_text);
            }
        }
    
        public MsgAdapter(List<Msg> msgList) {
            this.msgList = msgList;
        }
    
        @Override
        public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
            View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.item_msg, parent, false);
            return new ViewHolder(view);
        }
    
        @Override
        public void onBindViewHolder(ViewHolder holder, int position) {
            Msg msg = msgList.get(position);
            if (msg.getType() == msg.TYPE_RECEIVED) {
                holder.right_layout.setVisibility(View.GONE);
                holder.left_layout.setVisibility(View.VISIBLE);
                holder.left_imageView.setImageResource(R.drawable.left);
                holder.left_textView.setText(msg.getText());
            }else {
                holder.right_layout.setVisibility(View.VISIBLE);
                holder.left_layout.setVisibility(View.GONE);
                holder.right_imageView.setImageResource(R.drawable.right);
                holder.right_textView.setText(msg.getText());
            }
        }
    
        @Override
        public int getItemCount() {
            return msgList.size();
        }
    }
    

    最后在MainActivity中使用MsgAdapter.

    public class MainActivity extends AppCompatActivity {
    
        private List<Msg> msgList = new ArrayList<>();
        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_main);
    
            initMsg();
            final RecyclerView recyclerView = (RecyclerView)findViewById(R.id.recycle_view);
            LinearLayoutManager layoutManager = new LinearLayoutManager(this);
            recyclerView.setLayoutManager(layoutManager);
            final MsgAdapter adapter = new MsgAdapter(msgList);
            recyclerView.setAdapter(adapter);
    
            final EditText input_text = (EditText)findViewById(R.id.input_text);
            Button send_button = (Button)findViewById(R.id.send_button);
            send_button.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    String content = input_text.getText().toString();
                    if (!"".equals(content)) {
                        Msg msg = new Msg(content, Msg.SENT);
                        msgList.add(msg);
                        adapter.notifyItemInserted(msgList.size() + 1);
                        recyclerView.scrollToPosition(msgList.size() + 1);
                        input_text.setText("");
                    }
                }
            });
        }
    
        private void initMsg() {
            for (int i = 0; i < 3; i++) {
                Msg msg0 = new Msg("How are you?", 0);
                Msg msg1 = new Msg("I am fine, thank you. And you?", 1);
                Msg msg2 = new Msg("I am fine, too.", 0);
    
                msgList.add(msg0);
                msgList.add(msg1);
                msgList.add(msg2);
            }
        }
    }
    

    由上面的例子可以看出,ListView和RecyclerView的区别,主要在MsgAdapter的创建上.ListView的Adapter创建方式比较简单,只需要重写getView一个方法,而RecyclerView则需要重写onCreateViewHolder,onBindViewHoler和getItemsCount的3个方法.RecyerView实现方法的增加,方便了设计者对渲染过程的控制.其中的getView方法,被拆分成onCreateViewHolder和onBindViewHoler两个实现过程,在getItemsCount方法中,可以方便的控制渲染条数,比如,让最后一条不显示.
    对比学习能够在加深理解的同时,掌握各自的不同,从而方便我们面对对具体问题的解决方式.
    具体Demo如下:ListView和RecyclerView.

    相关文章

      网友评论

        本文标题:ListView和RecyclerView

        本文链接:https://www.haomeiwen.com/subject/mgvhqxtx.html