IT数码 购物 网址 头条 软件 日历 阅读 图书馆
TxT小说阅读器
↓语音阅读,小说下载,古典文学↓
图片批量下载器
↓批量下载图片,美女图库↓
图片自动播放器
↓图片自动播放器↓
一键清除垃圾
↓轻轻一点,清除系统垃圾↓
开发: C++知识库 Java知识库 JavaScript Python PHP知识库 人工智能 区块链 大数据 移动开发 嵌入式 开发工具 数据结构与算法 开发测试 游戏开发 网络协议 系统运维
教程: HTML教程 CSS教程 JavaScript教程 Go语言教程 JQuery教程 VUE教程 VUE3教程 Bootstrap教程 SQL数据库教程 C语言教程 C++教程 Java教程 Python教程 Python3教程 C#教程
数码: 电脑 笔记本 显卡 显示器 固态硬盘 硬盘 耳机 手机 iphone vivo oppo 小米 华为 单反 装机 图拉丁
 
   -> 移动开发 -> 【Android】第2章 | ListView & Adapter | 知识点总结 | 包含Demo -> 正文阅读

[移动开发]【Android】第2章 | ListView & Adapter | 知识点总结 | 包含Demo

运行环境


Android Studio 2020.3.1
在这里插入图片描述

1. ListView 与 Spinner组件


1.1 ListView 列表视图 Demo4


Android官网关于ListView的帮助文档:>>传送门<<
在这里插入图片描述
通过上图可以观察到ListViewView的间接子类。
ListView主要用于显示可垂直滚动的视图集合,其中每个视图都位于列表中上一个视图的正下方。

ListView是一个未知详细信息的Adapter View,比如类型和内容等信息。

ListView 根据需要从List Adapter请求视图,例如在用户上下滚动时显示新视图。
(其中Adapter可以使用Android自带的比如ArrayAdapter、SimpleAdapter,除此之外也可以使用继承的类)
范例:继承BaseAdapter类实现MyAdapter
代码模板:

private class MyAdapter extends BaseAdapter {

      // override other abstract methods here

      @Override
      public View getView(int position, View convertView, ViewGroup container) {
          if (convertView == null) {
              convertView = getLayoutInflater().inflate(R.layout.list_item, container, false);
          }

          ((TextView) convertView.findViewById(android.R.id.text1))
                  .setText(getItem(position));
          return convertView;
      }
  }

ListView还有许多方法,这里只是简单入门,想知道更多请参考上面官网的帮助文档。

1.2 Spinner 下拉列表 Demo1


参考资料:>>传送门<<
在这里插入图片描述
Spinner是一次显示一个子对象并允许用户在其中进行选择的视图。微调器中的项目来自与此视图关联的适配器。
Spinner内的项目来源于其Adapter相关的View

1.3 ListView与Spinner的区别


相同点

  • 都是View的间接子类
  • 都是展示一组数据的组件
  • 都可以使用继承的Adapter类

不同点

  • ListView的项目会直接显示出来,而Spinner则是归纳到同一个组件,类似按钮,需要点击后才会显示所有的项目。
  • ListView适合购物商品、视频课程等这类的布局,而Spinner适合表单的填写,比如选择所在地区。

2. 对象转换


2.1 将XML配置文件的内容转化为Java对象 Demo2


在这里插入图片描述
比如获取string类型的数据
colors.xml

<?xml version="1.0" encoding="utf-8"?>
<resources>
    <color name="purple_200">#FFBB86FC</color>
    <color name="purple_500">#FF6200EE</color>
    <color name="purple_700">#FF3700B3</color>
    <color name="teal_200">#FF03DAC5</color>
    <color name="teal_700">#FF018786</color>
    <color name="black">#FF000000</color>
    <color name="white">#FFFFFFFF</color>
    <array name="testColors">
        <item>#f00</item>
        <item>#0f0</item>
        <item>#00f</item>
    </array>
    <string-array name="testColorNames">
        <item>Red</item>
        <item>Green</item>
        <item>Blue</item>
    </string-array>
</resources>
Resources resources = getResources();
String[] colorNames = resources.getStringArray(R.array.testColorNames);

2.2 将组件转化为Java对象


方法:findViewById(R.id.xxx)
范例:Button button = findViewById(R.id.myButton);

3. TypedArray


参考资料:>>传送门<<
在这里插入图片描述
官方解释:

Container for an array of values that were retrieved with Resources.Theme#obtainStyledAttributes(AttributeSet, int[], int, int) or Resources#obtainAttributes. Be sure to call recycle() when done with them. The indices used to retrieve values from this structure correspond to the positions of the attributes given to obtainStyledAttributes.

意思大概就是该对象用来读取XML文件里的配置,比如通过Java代码去控制APP里某个组件的字体大小等。

3.1 创建对象


dimens.xml

<?xml version="1.0" encoding="utf-8"?>
<resources>
    <array name="testDimens">
        <item>12sp</item>
        <item>16sp</item>
        <item>20sp</item>
    </array>

    <string-array name="testDimenNames">
        <item>Small</item>
        <item>Medium</item>
        <item>Big</item>
    </string-array>
</resources>
Resources resources = getResources();
String[] dimenNames= resources.getStringArray(R.array.testDimenNames);
TypedArray dimens = resources.obtainTypedArray(R.array.testDimens);

3.2 常用方法


在这里插入图片描述
范例:获取字体大小的属性

float dim = dimens.getDimension(i, 10.0f);

4. 监听事件


4.1 Spinner 监听事件


下拉列表选择第 i 个项时的监听事件:Demo1

ArrayAdapter<String> adapter = new ArrayAdapter<>(this, android.R.layout.simple_list_item_single_choice, cities);
sp.setAdapter(adapter);
sp.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
		@Override
		public void onItemSelected(AdapterView<?> adapterView, View view, int i, long l) {
		String city = cities[i];
}

        @Override
        public void onNothingSelected(AdapterView<?> adapterView) {}
});

4.2 ListView 监听事件


当列表的某个项被单击时

lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
	@Override
    public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
		
    }
});

4.3 ImageView 监听事件


图片被单击时

iv_call.setOnClickListener(new View.OnClickListener() {
	@Override
	public void onClick(View view) {
	Toast.makeText(context, "图片被单击!",Toast.LENGTH_LONG).show();
	}
});

5. Adapter


参考资料:>>传送门<<
在这里插入图片描述

  • Adapter是将数据绑定到UI界面上的桥接类。
  • Adapter负责创建显示每个项目的子View和提供对下层数据的访问。
  • Adapter充当Adapter View和该视图的基础数据之间的桥梁。
  • Adapter负责为数据集中的每个项目生成android.view.View。

5.1 ArrayAdapter Demo1


参考资料:>>传送门<<
在这里插入图片描述
构造方法:
在这里插入图片描述
范例:创建一个ArrayAdapter对象

String[] cities = resources.getStringArray(R.array.cities);
ArrayAdapter<String> adapter = new ArrayAdapter<>(this, android.R.layout.simple_list_item_single_choice, cities);

官方对ArrayAdapter的解释:

You can use this adapter to provide views for an AdapterView, Returns a view for each object in a collection of data objects you provide, and can be used with list-based user interface widgets such as ListView or Spinner.

By default, the array adapter creates a view by calling Object#toString() on each data object in the collection you provide, and places the result in a TextView. You may also customize(定制) what type of view is used for the data object in the collection. To customize what type of view is used for the data object, override getView(int, android.view.View, android.view.ViewGroup) and inflate a view resource.

大概意思是说Adapter可以用来提供视图,并且可以与基于列表的用户界面小部件(如ListView或Spinner)一起使用。则有:
spinner.setAdapter(myArrayAdapter);
ListView.setAdapter(myArrayAdapter);
如果要使用自定义的ArrapAdapter的话,需要继承该类并重写getView(int, android.view.View, android.view.ViewGroup)方法。

5.2 SimpleAdapter Demo5


参考资料:>>传送门<<

在这里插入图片描述

  • SimpleAdapter是将静态数据映射到XML文件中定义的视图的简单适配器。
  • 可以将支持列表的数据指定为map的ArrayList。
  • ArrayList中的每个条目对应于列表中的一行。
  • You also specify an XML file that defines the views used to display the row, and a mapping from keys in the Map to specific views.

  • 上面这句来自官方的解释,意思是可以指定定义用于显示行的视图的XML文件,以及从映射中的键到特定视图的映射。即相当于不同布局的嵌套使用比如:
    在这里插入图片描述
    类似于通讯录的界面,每一个联系人都有图像 + 名称 + 电话号码 + 呼叫按钮的布局,而所有的联系人又在同一个ListView组件中。

构造方法:
在这里插入图片描述
范例:创建 SimpleAdapter对象

String[] names = new String[] {"周星驰", "彭于晏", "买瓜的强子"};
String []phones = new String[] {"666", "520", "999"};
int [] picIds = new int [] {R.drawable.zhouxingchi, R.drawable.pengyuyan, R.drawable.liuhuaqiang};
ArrayList<HashMap<String, Object>> list = new ArrayList<>();
for (int i = 0; i < names.length; i++) {
	HashMap<String, Object> hashMap = new HashMap<>();
	hashMap.put(KEY_NAME, names[i]);
	hashMap.put(KEY_PHONE, phones[i]);
	hashMap.put(KEY_PIC_ID, picIds[i]);
	list.add(hashMap);
}
SimpleAdapter adapter = new SimpleAdapter(
this, 
list, 
R.layout.row_view,
new String[] {KEY_NAME, KEY_PHONE, KEY_PIC_ID},
new int []{R.id.row_view_tv_name, R.id.row_view_tv_phone, R.id.row_view_iv});

5.3 ArrayAdapter 与 SimpleAdapter 比较


相同点:

  • 都可用作组件的Adapter适配器
  • 都支持多元素的容器

不同点:

  • ArrayAdapter通常是存储数组型数据如List、Array等,而SimpleAdapter则用HashMap型数据

5.4 继承Adapter类的代码框架

以继承ArrayAdapter类为例:

public class PictureAdapter extends ArrayAdapter<Picture> {
    private Context context;
    private ArrayList<Picture> list;

    public PictureAdapter(@NonNull Context context, ArrayList<Picture> list) {
        super(context, android.R.layout.simple_list_item_1, list);
        this.context = context;
        this.list = list;
    }

    @NonNull
    @Override
    public View getView(int position, @Nullable View convertView, @NonNull ViewGroup parent) {
        View v;
        if(convertView == null){
            v = LayoutInflater.from(context).inflate(R.layout.row_view, null, false);
        } else{
            v = convertView;
        }
        ImageView iv = v.findViewById(R.id.row_view_iv);
        TextView tv = v.findViewById(R.id.row_view_tv);
        Picture picture = list.get(position);
        iv.setImageResource(picture.getPicId());;
        tv.setText(picture.getName());
        return v;
    }
}

6. Demo


6.1 实现一个可选择的列表框


实现效果

在这里插入图片描述
在这里插入图片描述
layout_main.xml

<?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"
    android:orientation="vertical"
    >

    <TextView
        android:id="@+id/tv_result"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="TextView" />

    <Spinner
        android:id="@+id/spinner"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        />
</LinearLayout>

strings.xml

<resources>
    <string name="app_name">test</string>
    <string-array name="cities">
        <item>Wenzhou</item>
        <item>Hangzhou</item>
        <item>Ningbo</item>
    </string-array>
</resources>

MainActivity.java

import androidx.appcompat.app.AppCompatActivity;
import android.content.res.Resources;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Spinner;
import android.widget.TextView;

public class MainActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.layout_main);
        Resources resources = getResources();
        String[] cities = resources.getStringArray(R.array.cities);
        TextView tv = findViewById(R.id.tv_result);
        Spinner sp = findViewById(R.id.spinner);
        ArrayAdapter<String> adapter = new ArrayAdapter<>(this, android.R.layout.simple_list_item_single_choice, cities);
        sp.setAdapter(adapter);
        sp.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> adapterView, View view, int i, long l) {
                String city = cities[i];
                tv.setText(city);
            }

            @Override
            public void onNothingSelected(AdapterView<?> adapterView) {}
        });
    }
}

6.2 实现通过列表框修改文本的颜色


实现效果

在这里插入图片描述
在这里插入图片描述
layout_main.xml

<?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"
    android:orientation="vertical">

    <TextView
        android:id="@+id/textView"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="Font" />

    <Spinner
        android:id="@+id/spinner"
        android:layout_width="match_parent"
        android:layout_height="wrap_content" />
</LinearLayout>

colors.xml

<?xml version="1.0" encoding="utf-8"?>
<resources>
    <color name="purple_200">#FFBB86FC</color>
    <color name="purple_500">#FF6200EE</color>
    <color name="purple_700">#FF3700B3</color>
    <color name="teal_200">#FF03DAC5</color>
    <color name="teal_700">#FF018786</color>
    <color name="black">#FF000000</color>
    <color name="white">#FFFFFFFF</color>
    <array name="testColors">
        <item>#f00</item>
        <item>#0f0</item>
        <item>#00f</item>
    </array>
    <string-array name="testColorNames">
        <item>Red</item>
        <item>Green</item>
        <item>Blue</item>
    </string-array>
</resources>

MainActivity.java

import androidx.appcompat.app.AppCompatActivity;
import android.content.res.Resources;
import android.content.res.TypedArray;
import android.graphics.Color;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Spinner;
import android.widget.TextView;
public class MainActivity extends AppCompatActivity {
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.layout_main);

        Spinner sp = findViewById(R.id.spinner);
        TextView tv = findViewById(R.id.textView);

        Resources resources = getResources();
        String[] colorNames = resources.getStringArray(R.array.testColorNames);
        ArrayAdapter<String> adapter = new ArrayAdapter<>(this, android.R.layout.simple_list_item_single_choice,colorNames);
        TypedArray testColors = resources.obtainTypedArray(R.array.testColors);
        sp.setAdapter(adapter);
        sp.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> adapterView, View view, int i, long l) {
                int color = testColors.getColor(i, Color.BLACK);
                tv.setTextColor(color);
            }
            @Override
            public void onNothingSelected(AdapterView<?> adapterView) {}
        });

    }
}

6.3 实现通过列表框修改文本的字体大小

实现效果
在这里插入图片描述
在这里插入图片描述
layout_main.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="match_parent">

    <TextView
        android:id="@+id/textView"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Font"
        />

    <Spinner
        android:id="@+id/spinner"
        android:layout_width="match_parent"
        android:layout_height="wrap_content" />
</LinearLayout>

values/dimens.xml

<?xml version="1.0" encoding="utf-8"?>
<resources>
    <array name="testDimens">
        <item>12sp</item>
        <item>16sp</item>
        <item>20sp</item>
    </array>

    <string-array name="testDimenNames">
        <item>Small</item>
        <item>Medium</item>
        <item>Big</item>
    </string-array>
</resources>

MainActivity.java

import androidx.appcompat.app.AppCompatActivity;

import android.content.res.Resources;
import android.content.res.TypedArray;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Spinner;
import android.widget.TextView;

public class MainActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.layout_main);
        TextView tv = findViewById(R.id.textView);
        Spinner sp = findViewById(R.id.spinner);
        Resources resources = getResources();
        String[] dimenNames= resources.getStringArray(R.array.testDimenNames);
        TypedArray dimens = resources.obtainTypedArray(R.array.testDimens);
        ArrayAdapter<String>adapter = new ArrayAdapter<>(this, android.R.layout.simple_list_item_1, dimenNames);
        sp.setAdapter(adapter);
        sp.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> adapterView, View view, int i, long l) {
                float dim = dimens.getDimension(i, 10.0f);
                tv.setTextSize(dim);
            }
            @Override
            public void onNothingSelected(AdapterView<?> adapterView) {

            }
        });
    }
}

6.4 实现通过列表框切换图片

实现效果
在这里插入图片描述
在这里插入图片描述
提前准备好的图片资源:
在这里插入图片描述
layout_main.xml

<?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"
    android:layout_width="match_parent"
    android:orientation="vertical"
    android:layout_height="match_parent">


    <ImageView
        android:id="@+id/imageView"
        android:layout_width="200dp"
        android:layout_height="200dp"
        android:scaleType="centerCrop"
        android:layout_gravity="center"
        app:srcCompat="@drawable/image1" />

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

MainActivity.java

import androidx.appcompat.app.AppCompatActivity;

import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.ListView;

public class MainActivity extends AppCompatActivity {
    int[] picIds = new int []{R.drawable.image1, R.drawable.image2, R.drawable.image3};
    String[] picNames = new String[]{"图片1", "图片2", "图片3"};
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.layout_main);

        ListView lv = findViewById(R.id.listview);
        ImageView iv = findViewById(R.id.imageView);
        ArrayAdapter<String> adapter = new ArrayAdapter<>(this, android.R.layout.simple_list_item_1, picNames);
        lv.setAdapter(adapter);
        lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
                int picId = picIds[i];
                iv.setImageResource(picId);
            }
        });
    }
}

6.5 实现手机通讯录的界面模拟


实现效果
在这里插入图片描述
row_view.xml
在这里插入图片描述

<?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"
    android:orientation="horizontal"
    android:gravity="center_vertical"
    android:layout_width="match_parent"
    android:layout_height="wrap_content">

    <ImageView
        android:id="@+id/row_view_iv"
        android:layout_width="100dp"
        android:layout_height="100dp"
        android:scaleType="centerCrop"
        app:srcCompat="@drawable/zhouxingchi" />

    <LinearLayout
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_weight="1"
        android:paddingLeft="10dp"
        android:gravity="center_vertical"
        android:orientation="vertical">

        <TextView
            android:id="@+id/row_view_tv_name"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:textSize="24sp"
            android:text="Name" />

        <TextView
            android:id="@+id/row_view_tv_phone"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:text="Phone" />

    </LinearLayout>

    <ImageView
        android:id="@+id/row_view_iv_call"
        android:layout_width="40dp"
        android:layout_height="40dp"
        android:paddingLeft="10dp"
        app:srcCompat="@android:drawable/sym_action_call" />
</LinearLayout>

layout_main.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:orientation="vertical"
    android:layout_height="match_parent">

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

MainActivity.java

package com.example;

import androidx.appcompat.app.AppCompatActivity;

import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.Toast;

import java.util.ArrayList;
import java.util.HashMap;

public class MainActivity extends AppCompatActivity {

    public static final String KEY_NAME="key_name";
    public static final String KEY_PHONE="key_phone";
    public static final String KEY_PIC_ID="key_pic_id";
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.layout_main);
        ListView lv = findViewById(R.id.listview);

        String[] names = new String[] {"周星驰", "彭于晏", "买瓜的强子"};
        String []phones = new String[] {"666", "520", "999"};
        int [] picIds = new int [] {R.drawable.zhouxingchi, R.drawable.pengyuyan, R.drawable.liuhuaqiang};
        ArrayList<HashMap<String, Object>> list = new ArrayList<>();
        for (int i = 0; i < names.length; i++) {
            HashMap<String, Object> hashMap = new HashMap<>();
            hashMap.put(KEY_NAME, names[i]);
            hashMap.put(KEY_PHONE, phones[i]);
            hashMap.put(KEY_PIC_ID, picIds[i]);
            list.add(hashMap);
        }
        SimpleAdapter adapter = new SimpleAdapter(this, list, R.layout.row_view,
                new String[] {KEY_NAME, KEY_PHONE, KEY_PIC_ID},
                new int []{R.id.row_view_tv_name, R.id.row_view_tv_phone, R.id.row_view_iv});
        lv.setAdapter(adapter);
        lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
                HashMap<String, Object> hashMap = list.get(i);
                String name = (String) hashMap.get(KEY_NAME);
                Toast.makeText(MainActivity.this, name, Toast.LENGTH_LONG).show();
            }
        });
    }
}

6.6 实现模拟通讯录里的呼叫功能

实现效果
在这里插入图片描述
该Demo的layout和第五个Demo的一样,就不重复Copy了,二者不同点在于这个ListView使用了继承的Adapter适配器类。

在这里插入图片描述
PhoneData.java

public class PhoneData {
    private String name;
    private String phone;
    private int picId;

    public PhoneData(String name, String phone, int picId) {
        this.name = name;
        this.phone = phone;
        this.picId = picId;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getPhone() {
        return phone;
    }

    public void setPhone(String phone) {
        this.phone = phone;
    }

    public int getPicId() {
        return picId;
    }

    public void setPicId(int picId) {
        this.picId = picId;
    }
}

PhoneDataAdapter.java

import android.content.Context;
import android.text.TextUtils;
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 android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;

import java.util.ArrayList;

public class PhoneDataAdapter extends ArrayAdapter<PhoneData> {
    private Context context;
    private ArrayList<PhoneData> list;

    public PhoneDataAdapter(@NonNull Context context ,ArrayList<PhoneData> list) {
        super(context, android.R.layout.simple_list_item_1, list);
        this.context = context;
        this.list = list;
    }

    @NonNull
    @Override
    public View getView(int position, @Nullable View convertView, @NonNull ViewGroup parent) {
        View v;
        if(convertView == null){
            v = LayoutInflater.from(context).inflate(R.layout.row_view, null, false);
        } else {
            v = convertView;
        }
        PhoneData phoneData = list.get(position);
        TextView tv_name = v.findViewById(R.id.row_view_tv_name);
        TextView tv_phone = v.findViewById(R.id.row_view_tv_phone);
        ImageView iv = v.findViewById(R.id.row_view_iv);
        ImageView iv_call = v.findViewById(R.id.row_view_iv_call);
        tv_name.setText(phoneData.getName());
        tv_phone.setText(phoneData.getPhone());
        iv.setImageResource(phoneData.getPicId());
        if(TextUtils.isEmpty(phoneData.getPhone())){
            iv_call.setVisibility(View.GONE);
        }
        iv_call.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Toast.makeText(context, "Calling " + phoneData.getPhone(), Toast.LENGTH_LONG).show();
            }
        });
        return v;
    }
}

MainActivity.java

import androidx.appcompat.app.AppCompatActivity;

import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.Toast;

import java.util.ArrayList;

public class MainActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.layout_main);
        ListView lv = findViewById(R.id.listview);
        ArrayList<PhoneData> list = new ArrayList<>();
        list.add(new PhoneData("周星驰", "666", R.drawable.zhouxingchi));
        list.add(new PhoneData("彭于晏", "520", R.drawable.pengyuyan));
        list.add(new PhoneData("买瓜的强子", "999", R.drawable.liuhuaqiang));
        PhoneDataAdapter adapter = new PhoneDataAdapter(this, list);
        lv.setAdapter(adapter);
        lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
//                PhoneData phoneData = list.get(i);
//                PhoneData phoneData = adapter.getItem(i);
                PhoneData phoneData = (PhoneData) lv.getItemAtPosition(i);
                Toast.makeText(MainActivity.this, phoneData.getName(), Toast.LENGTH_LONG).show();
            }
        });
    }
}

6.7 实现多行多列的列表

实现效果
在这里插入图片描述
layout_main.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:orientation="vertical"
    android:layout_height="match_parent">

    <TextView
        android:id="@+id/textView"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="TextView" />

    <GridView
        android:id="@+id/gridview"
        android:layout_width="match_parent"
        android:numColumns="3"
        android:stretchMode="columnWidth"
        android:layout_height="match_parent" />
</LinearLayout>

MainActivity.java

import androidx.appcompat.app.AppCompatActivity;

import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.GridView;
import android.widget.TextView;

import java.util.ArrayList;

public class MainActivity extends AppCompatActivity {

    ArrayList<String> list = new ArrayList();
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.layout_main);

        GridView gv = findViewById(R.id.gridview);
        TextView tv = findViewById(R.id.textView);
        for(int i = 0; i < 99; i++){
            String s = String.format("Item%02d", i);
            list.add(s);
        }
        ArrayAdapter<String> adapter = new ArrayAdapter<>(this, android.R.layout.simple_list_item_1, list);
        gv.setAdapter(adapter);
        gv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
                 String s = list.get(i);
                 tv.setText(s);
            }
        });
    }
}

6.8 实现展示风景的列表框


实现效果
在这里插入图片描述

在这里插入图片描述

row_view.xml
在这里插入图片描述

<?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"
    android:layout_width="match_parent"
    android:orientation="vertical"
    android:gravity="center"
    android:layout_height="wrap_content">

    <ImageView
        android:id="@+id/row_view_iv"
        android:layout_width="130dp"
        android:layout_height="130dp"
        android:scaleType="centerCrop"
        app:srcCompat="@drawable/image1" />

    <TextView
        android:id="@+id/row_view_tv"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="TextView" />
</LinearLayout>

layout_main.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:orientation="vertical"
    android:layout_height="match_parent">

    <TextView
        android:id="@+id/textView"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="TextView" />

    <GridView
        android:id="@+id/gridview"
        android:layout_width="match_parent"
        android:numColumns="2"
        android:stretchMode="columnWidth"
        android:layout_height="match_parent" />
</LinearLayout>

Picture.java

public class Picture {
    private String name;
    private int picId;

    public Picture(String name, int picId) {
        this.name = name;
        this.picId = picId;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public int getPicId() {
        return picId;
    }

    public void setPicId(int picId) {
        this.picId = picId;
    }
}

PictureAdapter.java

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 PictureAdapter extends ArrayAdapter<Picture> {
    private Context context;
    private ArrayList<Picture> list;

    public PictureAdapter(@NonNull Context context, ArrayList<Picture> list) {
        super(context, android.R.layout.simple_list_item_1, list);
        this.context = context;
        this.list = list;
    }

    @NonNull
    @Override
    public View getView(int position, @Nullable View convertView, @NonNull ViewGroup parent) {
        View v;
        if(convertView == null){
            v = LayoutInflater.from(context).inflate(R.layout.row_view, null, false);
        } else{
            v = convertView;
        }
        ImageView iv = v.findViewById(R.id.row_view_iv);
        TextView tv = v.findViewById(R.id.row_view_tv);
        Picture picture = list.get(position);
        iv.setImageResource(picture.getPicId());;
        tv.setText(picture.getName());
        return v;
    }
}

MainActivity.java

import androidx.appcompat.app.AppCompatActivity;

import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.GridView;
import android.widget.TextView;

import java.lang.reflect.Array;
import java.util.ArrayList;

public class MainActivity extends AppCompatActivity {

    ArrayList<Picture> list = new ArrayList<>();
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.layout_main);
        TextView tv = findViewById(R.id.textView);
        GridView gv = findViewById(R.id.gridview);

        for (int i = 0; i < 4; i++) {
            list.add(new Picture("图片1", R.drawable.image1));
            list.add(new Picture("图片2", R.drawable.image2));
            list.add(new Picture("图片3", R.drawable.image3));
        }
        PictureAdapter adapter = new PictureAdapter(this, list);
        gv.setAdapter(adapter);
        gv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
                Picture picture = adapter.getItem(i);
                tv.setText(picture.getName());
            }
        });
    }
}

6.9 实现多个地区多个景区的图片展示


实现效果
在这里插入图片描述
在这里插入图片描述
在这里插入图片描述
layout_scenery.xml
在这里插入图片描述

<?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"
    android:orientation="horizontal"
    android:gravity="center_vertical"
    android:layout_width="match_parent"
    android:layout_height="wrap_content">

    <ImageView
        android:id="@+id/iv_pic"
        android:layout_width="120dp"
        android:layout_height="80dp"
        android:layout_margin="10px"
        android:scaleType="centerCrop"
        app:srcCompat="@drawable/bj_beihai" />

    <TextView
        android:id="@+id/tv_name"
        android:layout_width="wrap_content"
        android:layout_height="100dp"
        android:layout_weight="1"
        android:gravity="center_vertical"
        android:text="北海"
        android:textColor="@color/teal_200"
        android:textSize="30sp" />
</LinearLayout>

layout_main.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="match_parent">

    <TextView
        android:id="@+id/tv_result"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="TextView" />

    <Spinner
        android:id="@+id/spinner"
        android:layout_width="match_parent"
        android:layout_height="wrap_content" />

    <ImageView
        android:id="@+id/imageView"

        android:layout_width="180dp"
        android:layout_height="100dp"
        android:layout_gravity="center"
        android:scaleType="centerCrop"
        />

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

接下来有两种方法实现最终的效果,一是使用ArrayAdapter,二是继承ArrayAdapter类。
方法一:
MainActivity.java

import androidx.appcompat.app.AppCompatActivity;

import android.content.res.Resources;
import android.content.res.TypedArray;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;

import java.util.ArrayList;
import java.util.HashMap;

public class MainActivity extends AppCompatActivity {

    // 标记 ListView 控件的 Layout内的HashMap键
    public static final String KEY_NAME = "key_name";
    public static final String KEY_PIC_ID = "key_pic_id";
    private int cityId = 0;                                 // 当前城市id
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.layout_main);

        // 创建城市信息、景区信息、图片ID
        String[] cities = new String[]{"温州", "贵阳", "杭州", "北京"};
        String[][] sceneris= new String[][] {
                {"江心屿", "大罗山", "洞头区"},
                {"花果园", "甲秀楼", "青岩古镇"},
                {"雷峰塔", "千岛湖", "西湖"},
                {"天安门", "北海", "天坛"}
        };
        int[][] picId = new int [][]{
                {R.drawable.wz_jiangxinyu, R.drawable.wz_daluoshan, R.drawable.wz_dongtouqu},
            {R.drawable.gy_huaguoyuan, R.drawable.gy_jiaxiulou, R.drawable.gy_qingyanguzhen},
            {R.drawable.hz_leifengta, R.drawable.hz_qiandaohu, R.drawable.hz_xihu},
            {R.drawable.bj_tiananmen, R.drawable.bj_beihai, R.drawable.bj_tiantan}
        };

        // 创建选择城市和景区的Adapter
        ArrayAdapter<String> adapter = new ArrayAdapter<>(this, android.R.layout.simple_list_item_1, cities);
        ArrayList<HashMap<String, Object>> list = new ArrayList<>();

        // 获取组件
        TextView tv = findViewById(R.id.tv_result);         // 显示 "城市:景区" 信息
        ImageView iv = findViewById(R.id.imageView);        // 显示 景区图片
        ListView lv = findViewById(R.id.lv_scenery);        // 选择 景区
        Spinner sp = findViewById(R.id.spinner);            // 选择 城市

        sp.setAdapter(adapter);                             // 设置spinner对应的adapter 选择城市

        // 当选择某个城市时的响应
        sp.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> adapterView, View view, int i, long l) {
                // 更改当前城市的 id
                cityId = i;

                // 显示城市信息
                tv.setText(cities[i]);

                // 默认显示该城市第一个景区
                iv.setImageResource(picId[i][0]); // 默认显示第一个景区

                // 根据选择的地点 更新景区选项
                list.clear();
                for(int j = 0; j < sceneris[i].length; ++j){
                    HashMap<String, Object> hashMap = new HashMap<>();
                    hashMap.put(KEY_NAME, sceneris[i][j]);
                    hashMap.put(KEY_PIC_ID, picId[i][j]);
                    list.add(hashMap);
                }

                // 创建列表框ListView的Adapter
                SimpleAdapter ad = new SimpleAdapter(MainActivity.this, list, R.layout.layout_scenery,
                        new String[] {KEY_NAME, KEY_PIC_ID},
                        new int [] {R.id.tv_name, R.id.iv_pic});
                lv.setAdapter(ad);

                // 当选择列表框的某个景区时的响应
                lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
                    @Override
                    public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
                        HashMap<String, Object> hashMap = list.get(i);      // 获取该景区的哈希表信息
                        String name = (String) hashMap.get(KEY_NAME);       // 获取景区名称
                        iv.setImageResource(picId[cityId][i]);              // 设置景区图片
                        tv.setText(cities[cityId] + ":" + name);            // 更新提示文本
                    }
                });
            }
            @Override
            public void onNothingSelected(AdapterView<?> adapterView) {}
        });
    }
}

方法二(layout都是一样的):
在这里插入图片描述

  • Adpter层负责编写继承ArrayAdapter的类,作为ListView组件的适配器
  • Controller层负责数据的交互,包括Spinner(显示城市名)和ListView(显示景区图片及其名称)展示的数据
  • Entity层负责编写存储景区实体的类,包括景区名景区图片ID两个属性

Landscape.java

public class Landscape {
    private String name;
    private int picId;
    public Landscape(String name, int picId) {
        this.name = name;
        this.picId = picId;
    }
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    public int getPicId() {
        return picId;
    }
    public void setPicId(int picId) {
        this.picId = picId;
    }
}

LandscapeAdapter.java

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 com.example.R;
import com.example.entity.Landscape;
 
import java.util.ArrayList;
 
public class LandscapeAdapter extends ArrayAdapter<Landscape> {
 
    private Context context;
    private ArrayList<Landscape> list;
 
    public LandscapeAdapter(@NonNull Context context, ArrayList<Landscape> list) {
        super(context, android.R.layout.simple_list_item_1, list);
        this.context = context;
        this.list = list;
    }
 
    @NonNull
    @Override
    public View getView(int position, @Nullable View convertView, @NonNull ViewGroup parent) {
        View v;
        if(convertView == null)
            v = LayoutInflater.from(context).inflate(R.layout.layout_row, null, false);
        else
            v = convertView;
        ImageView iv = v.findViewById(R.id.row_iv);
        TextView tv = v.findViewById(R.id.row_tv);
        Landscape landscape = list.get(position);
        iv.setImageResource(landscape.getPicId());
        tv.setText(landscape.getName());
        return v;
    }
}

LandscapeController.java

import com.example.R;
import com.example.entity.Landscape;
import java.util.ArrayList;
public class LandscapeController {
    private ArrayList<ArrayList<Landscape>> landscapeLists;
    private ArrayList<Landscape> curLandscapeList;
    private ArrayList<String> cityList;
    private int curCityPosition;
    private String curCityName;
    public LandscapeController() {
        init();
    }
    private void init(){
        landscapeLists = new ArrayList<>();
        cityList = new ArrayList<>();
        ArrayList<Landscape> list_wz = new ArrayList<>();
        list_wz.add(new Landscape("大罗山", R.drawable.wz_daluoshan));
        list_wz.add(new Landscape("洞头", R.drawable.wz_dongtou));
        list_wz.add(new Landscape("江心屿", R.drawable.wz_jiangxinyu));
 
        ArrayList<Landscape> list_hz = new ArrayList<>();
        list_hz.add(new Landscape("西湖", R.drawable.hz_xihu));
        list_hz.add(new Landscape("雷峰塔", R.drawable.hz_leifengta));
        list_hz.add(new Landscape("千岛湖", R.drawable.hz_qiandaohu));
 
        ArrayList<Landscape> list_gz = new ArrayList<>();
        list_gz.add(new Landscape("千户苗寨", R.drawable.gz_qianhumiaozhai));
        list_gz.add(new Landscape("梵净山", R.drawable.gz_fanjingshan));
        list_gz.add(new Landscape("织金洞", R.drawable.gz_zhijindong));
 
        insert("温州", list_wz);
        insert("杭州", list_hz);
        insert("贵州", list_gz);
    }
    private void insert(String name, ArrayList<Landscape> landscape){
        this.cityList.add(name);
        this.landscapeLists.add(landscape);
    }
 
    public ArrayList<Landscape> update(int position){
        this.curCityPosition = position;
        curLandscapeList = landscapeLists.get(position);
        curCityName = cityList.get(this.curCityPosition);
        return curLandscapeList;
    }
 
    public String getCurCityName(){
        return curCityName;
    }
    public int getCurCityPosition(){
        return curCityPosition;
    }
    public ArrayList<Landscape> getCurLandscapeList(){
        return curLandscapeList;
    }
    public ArrayList<String> getCityList(){
        return cityList;
    }
}

MainActivity.java

import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.Spinner;
import android.widget.TextView;
import com.example.adpter.LandscapeAdapter;
import com.example.controller.LandscapeController;
import com.example.entity.Landscape;
import java.util.ArrayList;
public class MainActivity extends AppCompatActivity {
    LandscapeController lc;
    TextView tv;
    ListView lv;
    ImageView iv;
    LandscapeAdapter adapter;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.layout_main);
 
        Spinner sp = findViewById(R.id.main_spinner);
        lv = findViewById(R.id.main_lv);
        tv = findViewById(R.id.main_tv_name);
        iv = findViewById(R.id.main_iv);
        lc = new LandscapeController();
        lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                updateListViewItem(position);
            }
        });
        ArrayAdapter<String> spAdapter = new ArrayAdapter<>(this, android.R.layout.simple_list_item_1, lc.getCityList());
        sp.setAdapter(spAdapter);
        sp.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                updateListView(position);
            }
 
            @Override
            public void onNothingSelected(AdapterView<?> parent) {}
        });
    }
    public void updateListViewItem(int position){
        Landscape landscape = adapter.getItem(position);
        tv.setText(lc.getCurCityName() + " : " + landscape.getName());
        iv.setImageResource(landscape.getPicId());
    }
    public void updateListView(int position){
        ArrayList<Landscape> list = lc.update(position);
        adapter = new LandscapeAdapter(this, list);
        lv.setAdapter(adapter);
        updateListViewItem(0);
    }
}
  移动开发 最新文章
Vue3装载axios和element-ui
android adb cmd
【xcode】Xcode常用快捷键与技巧
Android开发中的线程池使用
Java 和 Android 的 Base64
Android 测试文字编码格式
微信小程序支付
安卓权限记录
知乎之自动养号
【Android Jetpack】DataStore
上一篇文章      下一篇文章      查看所有文章
加:2021-10-26 12:19:17  更:2021-10-26 12:20:51 
 
开发: C++知识库 Java知识库 JavaScript Python PHP知识库 人工智能 区块链 大数据 移动开发 嵌入式 开发工具 数据结构与算法 开发测试 游戏开发 网络协议 系统运维
教程: HTML教程 CSS教程 JavaScript教程 Go语言教程 JQuery教程 VUE教程 VUE3教程 Bootstrap教程 SQL数据库教程 C语言教程 C++教程 Java教程 Python教程 Python3教程 C#教程
数码: 电脑 笔记本 显卡 显示器 固态硬盘 硬盘 耳机 手机 iphone vivo oppo 小米 华为 单反 装机 图拉丁

360图书馆 购物 三丰科技 阅读网 日历 万年历 2024年11日历 -2024/11/24 1:16:08-

图片自动播放器
↓图片自动播放器↓
TxT小说阅读器
↓语音阅读,小说下载,古典文学↓
一键清除垃圾
↓轻轻一点,清除系统垃圾↓
图片批量下载器
↓批量下载图片,美女图库↓
  网站联系: qq:121756557 email:121756557@qq.com  IT数码