In this tutorial we’ll use a CustomAdapter that populates the custom rows of the Android ListView with an ArrayList. Also to enhance the user experience, we’ll animate the ListView while scrolling.

在本教程中,我们将使用CustomAdapter使用ArrayList填充Android ListView的自定义行。 为了增强用户体验,我们将在滚动时为ListView设置动画。

Android ListView自定义适配器概述 (Android ListView Custom Adapter Overview)

The simplest Adapter to populate a view from an ArrayList is the ArrayAdapter. That’s what we’ll implement in this tutorial. There are other adapters as well, such as the CursorAdapter which binds directly to a result set from a Local SQLite Database and it uses a Cursor as it’s data source.

从ArrayList填充视图的最简单的Adapter是ArrayAdapter 。 这就是我们将在本教程中实现的。 还有其他适配器,例如CursorAdapter ,它直接绑定到本地SQLite数据库的结果集,并且使用Cursor作为数据源。

回收行 (Recycling Rows)

As a ListView is instantiated and the rows are populated such that the full height of the list is filled. After that no new row items are created in the memory. As the user scrolls through the list, items that leave the screen are kept in memory for later use and then every new row that enters the screen reuses an older row kept in the memory.

实例化ListView并填充行时,将填充列表的整个高度。 之后,不会在内存中创建新的行项目。 当用户滚动浏览列表时,离开屏幕的项目将保留在内存中以备后用,然后进入屏幕的每个新行都会重复使用保留在内存中的较旧行。

创建一个视图模板 (Creating a View template)

Let’s create a xml layout that presents the items in a row in a customised way.
row_item.xml

让我们创建一个xml布局,以自定义方式连续显示各项。
row_item.xml

<RelativeLayout xmlns:android="https://schemas.android.com/apk/res/android"android:layout_width="match_parent"android:layout_height="wrap_content"android:orientation="vertical"android:padding="10dp"><TextViewandroid:id="@+id/name"android:layout_width="wrap_content"android:layout_height="wrap_content"android:layout_alignParentTop="true"android:text="Marshmallow"android:textAppearance="?android:attr/textAppearanceSmall"android:textColor="@android:color/black" /><TextViewandroid:id="@+id/type"android:layout_width="wrap_content"android:layout_height="wrap_content"android:layout_below="@+id/name"android:layout_marginTop="5dp"android:text="Android 6.0"android:textColor="@android:color/black" /><ImageViewandroid:id="@+id/item_info"android:layout_width="wrap_content"android:layout_height="wrap_content"android:layout_alignParentEnd="true"android:layout_alignParentRight="true"android:layout_centerVertical="true"android:src="@android:drawable/ic_dialog_info" /><LinearLayoutandroid:layout_width="wrap_content"android:layout_height="wrap_content"android:layout_centerInParent="true"><TextViewandroid:id="@+id/version_heading"android:layout_width="wrap_content"android:layout_height="wrap_content"android:text="API: "android:textColor="@android:color/black"android:textStyle="bold" /><TextViewandroid:id="@+id/version_number"android:layout_width="wrap_content"android:layout_height="wrap_content"android:text="23"android:textAppearance="?android:attr/textAppearanceButton"android:textColor="@android:color/black"android:textStyle="bold" /></LinearLayout></RelativeLayout>

In this tutorial we’ll build an application that consists of list of rows displaying text descriptions and an info icon. Clicking the row would display the SnackBar with the text elements of that row. Clicking the info will display a SnackBar with information specific to that row.

在本教程中,我们将构建一个应用程序,该应用程序由显示文本描述和信息图标的行列表组成。 单击该行将显示带有该行文本元素的SnackBar。 单击信息将显示一个SnackBar,其中包含该行的特定信息。

项目结构 (Project Structure)

码 (Code)

We are creating a custom ListView of by subclassing ArrayAdapter with the DataModel as the object.
getView() is the method that returns the actual view used as a row within the ListView at a particular position.

我们通过将ArrayAdapter子类化为DataModel作为对象来创建自定义ListView。
getView()是一种返回实际视图的方法,该实际视图用作ListView中特定位置的行。

The content_main.xml contains the ListView as shown below.
content_main.xml

content_main.xml包含ListView,如下所示。
content_main.xml

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="https://schemas.android.com/apk/res/android"xmlns:tools="https://schemas.android.com/tools"android:layout_width="match_parent"android:layout_height="match_parent"xmlns:app="https://schemas.android.com/apk/res-auto"tools:context="com.journaldev.customlistview.MainActivity"app:layout_behavior="@string/appbar_scrolling_view_behavior"tools:showIn="@layout/activity_main"><ListViewandroid:id="@+id/list"android:layout_width="wrap_content"android:layout_height="wrap_content"/></RelativeLayout>

The data model that is contained in the ArrayList is shown below.
DataModel.java

ArrayList中包含的数据模型如下所示。
DataModel.java

public class DataModel {String name;String type;String version_number;String feature;public DataModel(String name, String type, String version_number, String feature ) {this.name=name;this.type=type;this.version_number=version_number;this.feature=feature;}public String getName() {return name;}public String getType() {return type;}public String getVersion_number() {return version_number;}public String getFeature() {return feature;}}

The CustomAdapter that populates the DataModel into the ListView is shown below.
CustomAdapter.java

下面显示了将DataModel填充到ListView中的CustomAdapter。
CustomAdapter.java

public class CustomAdapter extends ArrayAdapter<DataModel> implements View.OnClickListener{private ArrayList<DataModel> dataSet;Context mContext;// View lookup cacheprivate static class ViewHolder {TextView txtName;TextView txtType;TextView txtVersion;ImageView info;}public CustomAdapter(ArrayList<DataModel> data, Context context) {super(context, R.layout.row_item, data);this.dataSet = data;this.mContext=context;}@Overridepublic void onClick(View v) {int position=(Integer) v.getTag();Object object= getItem(position);DataModel dataModel=(DataModel)object;switch (v.getId()){case R.id.item_info:Snackbar.make(v, "Release date " +dataModel.getFeature(), Snackbar.LENGTH_LONG).setAction("No action", null).show();break;}}private int lastPosition = -1;@Overridepublic View getView(int position, View convertView, ViewGroup parent) {// Get the data item for this positionDataModel dataModel = getItem(position);// Check if an existing view is being reused, otherwise inflate the viewViewHolder viewHolder; // view lookup cache stored in tagfinal View result;if (convertView == null) {viewHolder = new ViewHolder();LayoutInflater inflater = LayoutInflater.from(getContext());convertView = inflater.inflate(R.layout.row_item, parent, false);viewHolder.txtName = (TextView) convertView.findViewById(R.id.name);viewHolder.txtType = (TextView) convertView.findViewById(R.id.type);viewHolder.txtVersion = (TextView) convertView.findViewById(R.id.version_number);viewHolder.info = (ImageView) convertView.findViewById(R.id.item_info);result=convertView;convertView.setTag(viewHolder);} else {viewHolder = (ViewHolder) convertView.getTag();result=convertView;}Animation animation = AnimationUtils.loadAnimation(mContext, (position > lastPosition) ? R.anim.up_from_bottom : R.anim.down_from_top);result.startAnimation(animation);lastPosition = position;viewHolder.txtName.setText(dataModel.getName());viewHolder.txtType.setText(dataModel.getType());viewHolder.txtVersion.setText(dataModel.getVersion_number());viewHolder.info.setOnClickListener(this);viewHolder.info.setTag(position);// Return the completed view to render on screenreturn convertView;}
}

In the above code we’ve added a onClickListener to the ImageView that displays a SnackBar when clicked with a description for the respective row.

在上面的代码中,我们向ImageView添加了onClickListener ,当单击时带有相应行的描述时显示SnackBar。

Also the list rows are animated when scrolled. The two animation xml resource files are given below.
down_from_top.xml

滚动时,列表行也具有动画效果。 下面给出了两个动画xml资源文件。
down_from_top.xml

<?xml version="1.0" encoding="utf-8"?>
<set xmlns:android="https://schemas.android.com/apk/res/android"android:shareInterpolator="@android:anim/decelerate_interpolator"><translateandroid:fromXDelta="0%" android:toXDelta="0%"android:fromYDelta="-100%" android:toYDelta="0%"android:duration="400" />
</set>

up_from_bottom.xml

up_from_bottom.xml

<?xml version="1.0" encoding="utf-8"?>
<set xmlns:android="https://schemas.android.com/apk/res/android"android:shareInterpolator="@android:anim/decelerate_interpolator"><translateandroid:fromXDelta="0%" android:toXDelta="0%"android:fromYDelta="100%" android:toYDelta="0%"android:duration="400" />
</set>

The MainActivity.java where the CustomAdapter is set to the ListView is defined below. Along with that a random ArrayList of DataModel objects is populated.

CustomAdapter设置为ListView的MainActivity.java定义如下。 随之而来的是随机填充的DataModel对象的ArrayList。

MainActivity.java

MainActivity.java

public class MainActivity extends AppCompatActivity {ArrayList<DataModel> dataModels;ListView listView;private static CustomAdapter adapter;@Overrideprotected void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);setContentView(R.layout.activity_main);Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);setSupportActionBar(toolbar);listView=(ListView)findViewById(R.id.list);dataModels= new ArrayList<>();dataModels.add(new DataModel("Apple Pie", "Android 1.0", "1","September 23, 2008"));dataModels.add(new DataModel("Banana Bread", "Android 1.1", "2","February 9, 2009"));dataModels.add(new DataModel("Cupcake", "Android 1.5", "3","April 27, 2009"));dataModels.add(new DataModel("Donut","Android 1.6","4","September 15, 2009"));dataModels.add(new DataModel("Eclair", "Android 2.0", "5","October 26, 2009"));dataModels.add(new DataModel("Froyo", "Android 2.2", "8","May 20, 2010"));dataModels.add(new DataModel("Gingerbread", "Android 2.3", "9","December 6, 2010"));dataModels.add(new DataModel("Honeycomb","Android 3.0","11","February 22, 2011"));dataModels.add(new DataModel("Ice Cream Sandwich", "Android 4.0", "14","October 18, 2011"));dataModels.add(new DataModel("Jelly Bean", "Android 4.2", "16","July 9, 2012"));dataModels.add(new DataModel("Kitkat", "Android 4.4", "19","October 31, 2013"));dataModels.add(new DataModel("Lollipop","Android 5.0","21","November 12, 2014"));dataModels.add(new DataModel("Marshmallow", "Android 6.0", "23","October 5, 2015"));adapter= new CustomAdapter(dataModels,getApplicationContext());listView.setAdapter(adapter);listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {@Overridepublic void onItemClick(AdapterView<?> parent, View view, int position, long id) {DataModel dataModel= dataModels.get(position);Snackbar.make(view, dataModel.getName()+"\n"+dataModel.getType()+" API: "+dataModel.getVersion_number(), Snackbar.LENGTH_LONG).setAction("No action", null).show();}});}@Overridepublic boolean onCreateOptionsMenu(Menu menu) {// Inflate the menu; this adds items to the action bar if it is present.getMenuInflater().inflate(R.menu.menu_main, menu);return true;}@Overridepublic boolean onOptionsItemSelected(MenuItem item) {// Handle action bar item clicks here. The action bar will// automatically handle clicks on the Home/Up button, so long// as you specify a parent activity in AndroidManifest.xml.int id = item.getItemId();//noinspection SimplifiableIfStatementif (id == R.id.action_settings) {return true;}return super.onOptionsItemSelected(item);}
}

The output of the application in action is shown below.

实际应用程序的输出如下所示。

This brings an end to this tutorial. You can download the final Android ListView Custom Adapter Project from the link below.

本教程到此结束。 您可以从下面的链接下载最终的Android ListView自定义适配器项目

Download Android ListView Custom Adapter Project下载Android ListView自定义适配器项目

Reference: API Guide List View

参考: API指南列表视图

翻译自: https://www.journaldev.com/10416/android-listview-with-custom-adapter-example-tutorial

带有自定义适配器示例教程的Android ListView相关推荐

  1. 自定义标签的使用jsp实例_JSP自定义标签示例教程

    自定义标签的使用jsp实例 Today we will look into JSP custom tags. Earlier we learned about JSP Action Elements, ...

  2. Android ListView示例教程

    We will learn how to create a simple Android ListView and launch a new activity on selecting a singl ...

  3. Android自定义操作栏示例教程

    In this tutorial we will create an app that consists of Android Custom Action Bar with a custom layo ...

  4. java 自定义注释_带有自定义注释的Java注释教程

    java 自定义注释 Java批注提供有关代码的信息,并且它们对其批注的代码没有直接影响. 在本教程中,我们将学习Java注释,如何编写自定义注释 ,注释用法以及如何使用反射来解析注释 . 注释是在J ...

  5. 带有自定义注释的Java注释教程

    Java注释提供有关代码的信息,并且它们对所注释的代码没有直接影响. 在本教程中,我们将学习Java注释,如何编写自定义注释 ,注释用法以及如何使用反射来解析注释 . 注释是在Java 1.5中引入的 ...

  6. ViewPager通过自定义适配器MyPagerAdapter实现界面导航(上标题)

    效果图: 一.这里是实现四个界面的左右拖动: VIewPager资源的四个VIew.xmlwen文件,这里只是简易事件四个界面 演示其中一个代码: view1.xml <?xml version ...

  7. Android Listview 自定义BaseAdapter的实现及Listview优化示例

    上一篇文章中我们讲了Android Listview SimpleAdapter的使用完整示例(实现用户列表)_左眼看成爱的博客-CSDN博客 本示例实现的效果图: 每个item中的checkbox选 ...

  8. mp8播放器 android 1.4,listview(自定义适配器)与媒体播放器android

    嘿家伙我在listview(自定义适配器)面临问题 . 我已经实现了播放音频(mp3文件)的媒体播放器的listview . 我已经在我的原始文件夹中包含了mp3文件 . 我知道这是一个循环视图 . ...

  9. XamarinAndroid组件教程RecylerView自定义适配器动画

    XamarinAndroid组件教程RecylerView自定义适配器动画 如果RecyclerViewAnimators.Adapters命名空间中没有所需要的适配器动画,开发者可以自定义动画.此时 ...

最新文章

  1. 2022-2028年中国手术室设备行业市场研究及前瞻分析报告
  2. 大规模分布式消息中间件考虑点
  3. 只有程序员才有的十大烦恼
  4. 河流为什么是弯曲的?
  5. 用c语言开发图形界面,「分享」C语言如何编写图形界面
  6. 两个不同的进程 虚拟地址相同_Linux的进程地址空间[一]
  7. SpringCloud-Config
  8. Rancher体系下容器日志采集
  9. 再看2015 --北漂程序员的成长史
  10. Flink 1.10 Container 环境实战
  11. 拓端tecdat|豆瓣大数据分析告诉你,高评分影视密码
  12. Spring Cloud学习系列第三篇【服务容错保护】
  13. win32com 读取excel
  14. 【DIY】用驱蚊器改装wifi中继器,wifi信号增强器
  15. Windows Server2003服务器密码忘记情况下,密码破解方法汇总
  16. [C++刷题笔记]——区间分解质数
  17. 【Excle数据透视表】如何移动数据透视表的位置
  18. 【会声会影教学】如何更改短视频速度
  19. 锤子终究走起了小米的路子
  20. 静态网网页设计成品下载

热门文章

  1. NRF24L01 + STC15F204EA 无线通信 源代码
  2. javascript数字补零
  3. Spring.NET学习笔记——目录(原)
  4. 80后营销人如何为理想插上丰满“羽翼”?
  5. 如何在网页中每小时更新一次数据?
  6. [转载] Python中不可变集合的使用frozenset()方法
  7. 基于docker的spark-hadoop分布式集群之二: 环境测试
  8. gitlab git 安装
  9. 说一下syslog日志吧~~~
  10. 设计模式之---解释器模式