ListView和Adapter

作者: Lee_5566 | 来源:发表于2019-08-15 14:06 被阅读8次
    image.png

    目录

    Adapter(适配器)

    Adapter是用来帮助填出数据的中间桥梁,简单点说吧:将各种数据以合适的形式显示在View中给用户看。
    Adapter有很多的接口、抽象类、子类可以使用。

    ArrayAdapter的参数说明:

    参数 描述
    第一个参数 -context上下文对象
    第二个参数 -每一个item的样式,可以使用系统提供,也可以自定义就是一个TextView
    第三个参数 -数据源,要显示的数据

    ListView

    ListView,列表视图,直接继承了AbsListView,是一个以垂直方式在项目中显示View视图的列表。

    ListView的数据项,来自一个继承了ListAdapter接口的适配器。

    下面开始实战使用.O(∩_∩)O

    使用ListView和Adapter

    MainActivity.java文件:

    package com.example.user.imagetest;
    
    import android.support.v7.app.AppCompatActivity;
    import android.os.Bundle;
    import android.widget.ArrayAdapter;
    import android.widget.ListView;
    
    public class MainActivity extends AppCompatActivity {
    
        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_main);
            // 获取资源
            ListView list1 = (ListView)findViewById(R.id.list_view);
            // 构建Adapter
            String[] arrayName = {"天下","第一","神剑","无双","剑姬"};
            ArrayAdapter<String> adapter1 = new ArrayAdapter<String>(this, R.layout.array_item, arrayName);
            // 为listview设置适配器
            list1.setAdapter(adapter1);
        }
    }
    
    

    然后需要在资源文件界面中加入ListView.
    主要的资源文件activity_main.xml:

    <?xml version="1.0" encoding="utf-8"?>
    <android.support.constraint.ConstraintLayout 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=".MainActivity">
    
    
        <ListView
            android:id="@+id/list_view"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            tools:layout_editor_absoluteX="0dp"
            tools:layout_editor_absoluteY="8dp" />
    
    </android.support.constraint.ConstraintLayout>
    

    另外,还需要添加适配器需要的资源文件.
    构建adapter的资源文件array_item.xml:

    <?xml version="1.0" encoding="utf-8"?>
    <TextView xmlns:android="http://schemas.android.com/apk/res/android"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:id="@+id/textview"
        android:textSize="24dp"
        android:textColor="#985647"
        android:shadowColor="#f0f"
        android:shadowDx="4"
        android:shadowDy="4">
    
    </TextView>
    
    

    运行效果

    image.png

    参考

    android中Adapter适配器的讲解
    Android--UI之ListView

    相关文章

      网友评论

        本文标题:ListView和Adapter

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