欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

Android—RecyclerView

程序员文章站 2022-05-15 19:27:49
...

 一、效果图

Android—RecyclerView


Android—RecyclerView

二、布局文件

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context="com.example.myapplication.RecycleActivity">
    <android.support.v7.widget.RecyclerView
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:id="@+id/re_recycle_view"
        >


    </android.support.v7.widget.RecyclerView>

</LinearLayout>


三、Java代码

package com.example.myapplication;

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

public class RecycleActivity extends AppCompatActivity {

    private RecyclerView re_recycle_view;
    private String[] city;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_recycle);
        re_recycle_view = (RecyclerView) findViewById(R.id.re_recycle_view);
        city = new String[]{"长沙市","衡阳市","益阳市","常德市","株洲市"};


        //设置适配器
        re_recycle_view.setAdapter(new MyAdapter());
        //设置recycleView的排列方式
        re_recycle_view.setLayoutManager(new LinearLayoutManager(this,LinearLayoutManager.VERTICAL,false));
    }

    class MyAdapter extends RecyclerView.Adapter{
        class MyViewHolder extends RecyclerView.ViewHolder{
            private TextView textView;

            public MyViewHolder(View itemView) {
                super(itemView);
                textView= (TextView) itemView.findViewById(android.R.id.text1);
            }
        }
        @Override
        public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {

            View v=getLayoutInflater().inflate(android.R.layout.simple_list_item_1,null);
            return new MyViewHolder(v);
        }

        @Override
        public void onBindViewHolder(RecyclerView.ViewHolder holder, int position) {
                 MyViewHolder myViewHolder= (MyViewHolder) holder;
            myViewHolder.textView.setText(city[position]);
        }

        @Override
        public int getItemCount() {
            return city.length;
        }
    }
}

设置recycleview 的排列方式的时候,能够设置是横向排列也可是纵向,也可设置反转(true ),也可设置其它布局。


相关标签: RecycleView