Android--- UI组件AdapterView and 适配器Adapter

Android--- AdapterView and Adapter

  • 适配器 -- Adapter
  • UI控件 -- AdapterView
    • ListView
      • 简单的ListView实现
      • 图文ListView实现
      • ListView的监听函数
    • GridView
    • Spinner
    • AdapterViewFlipper 和 StackView

适配器 – Adapter

  • Adapter是UI控件和实际数据之间的桥梁,通过adapter将数据展示到UI上
  • Adapter本身只是一个接口,Adapter及其子类的继承关系图
    Android--- UI组件AdapterView and 适配器Adapter_第1张图片
  • Adapter常用的实现类如下。
  • ArrayAdapter: 简单、易用的Adapter。通常用于将数组或List集合的多个值包装成多个列表项。
  • SimpleAdapter: 并不简单、功能强大的Adapter.可用于将List集合的多个对象包装成多个列表项。
  • SimpleCursorAdapter: 与SimpleAdapter基本相似,只是用于包装Cursor提供的数据。
  • BaseAdapter: 通常用于被扩展。扩展BaseAdapter可以对各列表项进行最大限度的定制。

UI控件 – AdapterView

  • AdapterView是常用的安卓UI控件
  • AdapterView继承了ViewGroup.它的本质是容器。
  • AdapterView显示的多个“列表项”由Adapter提供。调用AdapterView的**setAdapter(Adapter)**方法设置Adapter即可
  • Adapter是UI控件和实际数据之间的桥梁,通过adapter将数据展示到UI上
  • AdapterView是一个抽象类, 具体继承关系如下
    Android--- UI组件AdapterView and 适配器Adapter_第2张图片
  • 常用的实体类为第四行, 注意Gallery已经被淘汰, 可以用HorizontalScrollView
  • ListView也可用RecyclerView替代

ListView

简单的ListView实现

定义一个item布局文件(list中的每一项) – list_item.xml


<TextView xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:textSize="24sp"
    android:id = "@+id/listItem"
    >
TextView>

定义一个listView布局文件 – list_view.xml


<LinearLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    android:gravity="center">

    <ListView
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:id="@+id/myList"/>

LinearLayout>

*Android--- UI组件AdapterView and 适配器Adapter_第3张图片

使用Adapter

package com.example.homework2;

import androidx.appcompat.app.AppCompatActivity;
import android.content.Intent;
import android.graphics.Point;
import android.os.Bundle;
import android.view.Display;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.TextView;

import java.util.ArrayList;

public class MainActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.list_view);

        Display display = getWindowManager().getDefaultDisplay();
        Point size = new Point();
        display.getSize(size);
        int height = size.y;

        String[] items = new String[]{"Apple", "Mongo", "Pear", "Grape", "Banana", "Strawberry", "Blackberry", "Raspberry", "Peach", "Watermelon", "Cherry", "DragonFruit"};
        final ArrayList<String> list = new ArrayList<>();

        for (int i = 0; i < items.length; i++) {
            list.add(items[i]);
        }

        ListView listview = findViewById(R.id.myList);
        listview.setAdapter(new ArrayAdapter<String>(this, R.layout.list_item, list) {
            @Override
            public View getView(int position, View convertView, ViewGroup parent) {
                View view = super.getView(position, convertView, parent);
                TextView textView = (view.findViewById(R.id.listItem));
                textView.setMinHeight(0);
                textView.setMinimumHeight(0);
                textView.setHeight(height/ items.length);
                return view;
            }
        });
}

输出结果

Android--- UI组件AdapterView and 适配器Adapter_第4张图片

图文ListView实现

定义一个listView布局文件


<LinearLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    android:gravity="center">

    <ListView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:id="@+id/lv1"
        android:drawSelectorOnTop="true" />
        
LinearLayout>
————————————————
版权声明:本文为CSDN博主「0x2015」的原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接及本声明。
原文链接:https://blog.csdn.net/w57685321/article/details/78267051

**定义一个item布局文件(list中的每一项) **


<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent">
    <ImageView
        android:id="@+id/img"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:paddingStart="10dp"
        android:adjustViewBounds="true"
        android:maxWidth="100dp"/>
    <LinearLayout
        android:layout_width="wrap_content"
        android:layout_height="match_parent"
        android:orientation="vertical">
        <TextView
            android:id="@+id/title"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content" />
        <TextView
            android:id="@+id/author"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content" />
    LinearLayout>
LinearLayout>
————————————————
版权声明:本文为CSDN博主「0x2015」的原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接及本声明。
原文链接:https://blog.csdn.net/w57685321/article/details/78267051

创建一个Simple Adapter, 将数据绑定到UI

package com.example.admin.test3;

import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.TextView;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class Test2Activity extends AppCompatActivity{

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_test2);
        //获取布局中的ListView
        final ListView lv1 = (ListView)findViewById(R.id.lv1);
        //获取图片资源文件
        int [] images = new int[]{R.drawable.img4,R.drawable.img5,R.drawable.img6,R.drawable.img7};
        String []title = new String[]{"实战大数据——","白话深度学习与","Unity 3D\\2D手机游戏开发:从学习","Web前端自动化构"};
        String []author = new String[]{"许国根,贾瑛","高扬","金玺曾","[澳]斯特凡·鲍姆加"};
        //将上面的数据添加到List集合中
        List<Map<String,Object>> listItems = new ArrayList<Map<String,Object>>();
        for(int i=0;i<title.length;i++){
            //每一行数据都是一个Object,然后存入Map中,String自己指定
            Map<String,Object> map = new HashMap<String,Object>();
            map.put("img",images[i]);
            map.put("title",title[i]);
            map.put("author",author[i]);
            listItems.add(map);
        }
        //关键的SimpleAdapter
        /* 关于SimpleAdapter,使用SimpleAdapter的最大难点在于创建SimpleAdapter对象,它需要5个参数:
		>* 第一个参数:上下文,这个不用多说,写this即可。
		>* 第二个参数:该参数应该是一个 List< Map> 类型的集合对象,该集合中每个Map对象生成一个列表项。
		>* 第三个参数:该参数指定一个界面布局的ID,这里使用的自己创建的xml布局文件。
		>* 第四个参数:该参数是一个String[]类型的参数,该参数决定提取Map对象中哪些key对应的value来生成列表项,所以填写map.put(key,Value)对应的key即可。
		>* 第五个参数:该参数是一个int[]类型的参数,该参数决定填充哪些组件,填写自定义的xml布局文件中控件的ID即可,相当于把第四个参数指定的数据填充到第五个控件指定的控件中,与第四个参数形成对应关系*/
        SimpleAdapter adapter = new SimpleAdapter(
                					this,
                					listItems,
                					R.layout.simpleadaitem,
                					new String[]{"img","title","author"},
                					new int[]{R.id.img,R.id.title, R.id.author});
        lv1.setAdapter(adapter);
    }
}
————————————————
版权声明:本文为CSDN博主「0x2015」的原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接及本声明。
原文链接:https://blog.csdn.net/w57685321/article/details/78267051

Android--- UI组件AdapterView and 适配器Adapter_第5张图片

ListView的监听函数

OnItemClickListener – 可以处理视图中单个条目的点击事件

listview.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                String selectedItem = (String) parent.getItemAtPosition(position);
                Intent intent = new Intent(view.getContext(), WebActivity.class);
                intent.putExtra("item_name", selectedItem);
                startActivity (intent);
            }
        });

OnScrollListener – ListView的滚动事件,监听滚动事件,可以做到下拉刷新,下拉显示更多列表的操作

 lv1.setOnScrollListener(new AbsListView.OnScrollListener() {
            @Override
            public void onScrollStateChanged(AbsListView absListView, int i) {
                switch(i){
                    case SCROLL_STATE_FLING:
                        Log.i("Main", "用户在手指离开屏幕之前,由于用力滑了一下,视图仍在滚动");
                        break;
                    case SCROLL_STATE_IDLE:
                        Log.i("Main", "视图已经停止滚动");
                        break;
                    case SCROLL_STATE_TOUCH_SCROLL:
                        Log.i("Main", "手指没有离开屏幕,视图正在滑动");
                        break;
                }
            }
            @Override
            public void onScroll(AbsListView absListView, int i, int i1, int i2) {

            }
        });
————————————————
版权声明:本文为CSDN博主「0x2015」的原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接及本声明。
原文链接:https://blog.csdn.net/w57685321/article/details/78267051

ExpandableListView

GridView

创建一个GridView布局文件


<androidx.constraintlayout.widget.ConstraintLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity">
 
    
    <GridView
        android:id="@+id/idGVcourses"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:horizontalSpacing="6dp"
        android:numColumns="2"
        android:verticalSpacing="6dp" />
 
androidx.constraintlayout.widget.ConstraintLayout>

创建每个item的布局文件



<androidx.cardview.widget.CardView
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="120dp"
    android:layout_gravity="center"
    android:layout_margin="5dp"
    app:cardCornerRadius="5dp"
    app:cardElevation="5dp">
 
    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="vertical">
 
        <ImageView
            android:id="@+id/idIVcourse"
            android:layout_width="100dp"
            android:layout_height="100dp"
            android:layout_gravity="center"
            android:src="@mipmap/ic_launcher" />
 
        <TextView
            android:id="@+id/idTVCourse"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:text="@string/app_name"
            android:textAlignment="center" />
 
    LinearLayout>
 
androidx.cardview.widget.CardView>

创建一个Modal类用来储存数据

public class CourseModel {
 
    // string course_name for storing course_name
    // and imgid for storing image id.
    private String course_name;
    private int imgid;
 
    public CourseModel(String course_name, int imgid) {
        this.course_name = course_name;
        this.imgid = imgid;
    }
 
    public String getCourse_name() {
        return course_name;
    }
 
    public void setCourse_name(String course_name) {
        this.course_name = course_name;
    }
 
    public int getImgid() {
        return imgid;
    }
 
    public void setImgid(int imgid) {
        this.imgid = imgid;
    }
}

创建一个Adapter, extend ArrayAdapter

import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.TextView;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import java.util.ArrayList;
 
public class CourseGVAdapter extends ArrayAdapter<CourseModel> {
    public CourseGVAdapter(@NonNull Context context, ArrayList<CourseModel> courseModelArrayList) {
        super(context, 0, courseModelArrayList);
    }
 
    @NonNull
    @Override
    public View getView(int position, @Nullable View convertView, @NonNull ViewGroup parent) {
        View listitemView = convertView;
        if (listitemView == null) {
            // Layout Inflater inflates each item to be displayed in GridView.
            listitemView = LayoutInflater.from(getContext()).inflate(R.layout.card_item, parent, false);
        }
        CourseModel courseModel = getItem(position);
        TextView courseTV = listitemView.findViewById(R.id.idTVCourse);
        ImageView courseIV = listitemView.findViewById(R.id.idIVcourse);
        courseTV.setText(courseModel.getCourse_name());
        courseIV.setImageResource(courseModel.getImgid());
        return listitemView;
    }
}

使用Adapter

import android.os.Bundle;
import android.widget.GridView;
import androidx.appcompat.app.AppCompatActivity;
import java.util.ArrayList;
 
public class MainActivity extends AppCompatActivity {
 
    GridView coursesGV;
 
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
       
        coursesGV = findViewById(R.id.idGVcourses);
       
        ArrayList<CourseModel> courseModelArrayList = new ArrayList<CourseModel>();
        courseModelArrayList.add(new CourseModel("DSA", R.drawable.ic_gfglogo));
        courseModelArrayList.add(new CourseModel("JAVA", R.drawable.ic_gfglogo));
        courseModelArrayList.add(new CourseModel("C++", R.drawable.ic_gfglogo));
        courseModelArrayList.add(new CourseModel("Python", R.drawable.ic_gfglogo));
        courseModelArrayList.add(new CourseModel("Javascript", R.drawable.ic_gfglogo));
        courseModelArrayList.add(new CourseModel("DSA", R.drawable.ic_gfglogo));
 
        CourseGVAdapter adapter = new CourseGVAdapter(this, courseModelArrayList);
        coursesGV.setAdapter(adapter);
    }
}

Android--- UI组件AdapterView and 适配器Adapter_第6张图片

Spinner

创建布局文件



 
<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="com.geeksforgeeks.Spinner.MainActivity">
 
    
    <Spinner
        android:id="@+id/coursesspinner"
        android:layout_height="50dp"
        android:layout_width="160dp"
        android:layout_marginEnd="10dp"
        android:layout_marginStart="10dp"   
        android:layout_marginBottom="10dp"
        android:layout_marginTop="10dp"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent"/>
   
android.support.constraint.ConstraintLayout>

创建Java文件

import android.support.v7.app.AppCompatActivity;
import android.widget.AdapterView;
import android.view.View;
import android.os.Bundle;
import android.widget.ArrayAdapter;
import android.widget.Spinner;
import android.os.Bundle;
 
// Main Activity implements Adapter view
public class MainActivity
    extends AppCompatActivity
    implements AdapterView.OnItemSelectedListener {
 
    // create array of Strings
    // and store name of courses
    String[] courses = { "C", "Data structures",
                        "Interview prep", "Algorithms",
                        "DSA with java", "OS" };
 
    @Override
    protected void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
 
        // Take the instance of Spinner and
        // apply OnItemSelectedListener on it which
        // tells which item of spinner is clicked
        Spinner spino = findViewById(R.id.coursesspinner);
        spin.setOnItemSelectedListener(this);
 
        // Create the instance of ArrayAdapter
        // having the list of courses
        ArrayAdapter ad = new ArrayAdapter(
                		  this,
               			  android.R.layout.simple_spinner_item,
                		  courses);
 
        // set simple layout resource file
        // for each item of spinner, a simple text view 
        ad.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        spino.setAdapter(ad);
    }
 
    // Performing action when ItemSelected
    // from spinner, Overriding onItemSelected method
    @Override
    public void onItemSelected(AdapterView<*> arg0, View arg1, int position, long id) {
        // make toastof name of course
        Toast.makeText(getApplicationContext(), courses[position], Toast.LENGTH_LONG).show();
    }
 
    @Override
    public void onNothingSelected(AdapterView<*> arg0)
    {
        // Auto-generated method stub
    }
}

Android--- UI组件AdapterView and 适配器Adapter_第7张图片

AdapterViewFlipper 和 StackView

  • AdapterViewFlipper可以实现画面自动播放
  • SatckView可以实现叠加效果
    Android--- UI组件AdapterView and 适配器Adapter_第8张图片

你可能感兴趣的:(安卓,Android,android,java)