Application of list view (ListView) in Android Studio

Table of contents

introduction

1. The role of list view

2. Working principle and working method of list view

3. Prepare data sources

4. Use of adapter

5. List view in layout file

6. Customize list item layout

7. List item click event processing

8. List optimization

10. Sample code and demonstration

11. Summary and Outlook

References:


introduction

        Welcome to this blog! In mobile application development, ListView is an indispensable component. It provides us with a concise and powerful way to display and manage large amounts of data . Whether displaying contact lists , product information , or message records , list views allow us to present data to users in a clear and orderly manner.

        In today's mobile application development, Android Studio is our right-hand assistant. It provides a rich set of development tools and features that enable us to easily build applications that meet user expectations. In Android Studio, using list views is a very common requirement , so mastering the use of list views is one of the essential skills for every developer.

        In this blog, we will delve into the use of list views in Android Studio . we will learn

  • How to define and configure list view in layout file ,
  • How to prepare data sources
  • How to associate data with list view using adapter .
  •   We will also learn how to customize the appearance of list items according to our needs and handle interactive operations such as click events on list items .
  • Finally, we’ll also share some optimization tips to improve your app’s performance and user experience.

        Whether you are a beginner or an experienced developer, this blog will provide you with comprehensive and practical knowledge. Let's start exploring the wonderful world of list views in Android Studio!

1. The role of list view

        List view plays an important role in Android application development. It provides us with an intuitive and efficient way to display and manage large amounts of data. Whether displaying contact lists, product information, or message records, list views can present data to users in a clear and orderly manner and provide rich interactivity.

Here are some common use cases for list views:

  1. Displaying a contact list: A list view is ideal when an app needs to display a list of contacts. Through the list view, we can display the contact's name, avatar and other information in each list item, and can set click events for each list item, such as making a call or sending a text message.

  2. Product list: E-commerce applications usually need to display a large amount of product information. Through list view, we can display products in a clear layout, including product name, price, pictures, etc. Users can browse products through the scrolling list and select the products of interest to purchase or view details.

  3. Message list: Chat applications or notification applications usually need to display a large number of message records. Through the list view, we can display the messages in chronological order and display the sender, content, time and other information in each list item. Users can scroll through the list to view historical messages and perform replies or other operations.

  4. Setting interface: The setting interface often contains multiple options or function items. Through list view, we can display each setting item in the form of a list, allowing users to easily browse and change various settings of the application.

In addition to the above scenarios, list views can also be used to display various types of data such as music playlists, book catalogs, and news lists. With proper layout and interaction design, list views can provide a good user experience and help users find the information they need quickly and accurately.

2. Working principle and working method of list view

List view is a commonly used UI component in Android development, used to display large data lists. Its principles and working methods mainly include the following aspects:

  1. Data source: List views require a data source to provide the displayed data. The data source can be an array, collection or database, etc. Each data item represents an entry in the list.

  2. Adapter: The adapter is the bridge between the data source and the list view. It is responsible for associating data items with list item views so that the data is displayed correctly. Adapters can inherit from the BaseAdapter class, or use preset adapter classes such as ArrayAdapter and CursorAdapter.

  3. List item view: Each data item will correspond to a list item view, which is used to display specific data content. List item views can be defined through layout files or dynamically created using code. It usually contains multiple controls (such as TextView, ImageView, etc.) for displaying various properties of data items.

  4. List item reuse: In order to improve performance and reduce memory usage, the Android system adopts a list item reuse mechanism. As the list scrolls, list items that extend beyond the screen are recycled and reused instead of creating new list items each time. This mechanism needs to be implemented in the adapter's getView() method.

  5. List item click event: The list view can listen to the user's click event on the list item. When the user clicks on a list item, a listener can be set to perform corresponding operations, such as opening a new interface, displaying detailed information, etc.

  6. List view update: When the data source changes, the list view needs to be notified in time to update. This can be achieved by calling the adapter's notifyDataSetChanged() method, which triggers the list view to reload the data and refresh the interface.

       [Figure 1 Schematic diagram of Adapter adapter]

Overall, the workflow of a list view is as follows:

  1. Prepare data sources, including obtaining data or querying data from databases.
  2. Create an adapter and associate the data source with the adapter.
  3. Set the adapter to the list view.
  4. The list view creates a corresponding number of list item views based on the number of data items in the adapter.
  5. When the list is scrolled, the list item reuse mechanism will reuse the already created list item view to improve performance.
  6. The list item view displays content based on the data in the data source.
  7. The user interacts with the list items, such as clicking on a list item.
  8. Update the data source as needed and then notify the adapter for data updates.
  9. After the adapter receives the data update notification, it triggers the list view to reload the data and refresh the interface.

By understanding and mastering the principles and working methods of list views, developers can better use and customize list views to achieve various complex data display requirements.

3. Prepare data sources

        Define the data model class: Create a data model class to represent each item in the list. This class should contain project-related properties and methods.

public class Item {
    private String title;  // 标题
    private String description;  // 描述

    // 构造函数、Getter 和 Setter 方法等

    // 可以根据需要扩展其他属性和方法
}

4. Use of adapter

The adapter plays a very important role in the list view. It is responsible for associating the data source with the list view and deciding how to display the data in the list items. Here is a basic adapter usage example:

  1. Prepare the data source: First, prepare an array or collection containing data as the data source. For example, we can create an ArrayList that stores strings as a data source:
    ArrayList<String> dataList = new ArrayList<>(); 
    dataList.add("Item 1"); 
    dataList.add("Item 2"); 
    dataList.add("Item 3");
  2. Create an adapter: Next, create an adapter class and inherit from BaseAdapter or its subclasses (such as ArrayAdapter, CursorAdapter, etc.). In the adapter class, we need to implement several key methods.
    public class MyAdapter extends BaseAdapter { 
        private ArrayList<String> mDataList; 
        public MyAdapter(ArrayList<String> dataList) { 
            mDataList = dataList; 
        } 
    
        @Override 
        public int getCount() { 
            return mDataList.size(); 
        } 
    
        @Override 
        public Object getItem(int position) { 
            return mDataList.get(position); 
        } 
    
        @Override 
        public long getItemId(int position) { 
            return position; 
        } 
    
        @Override 
        public View getView(int position, View convertView, ViewGroup parent) { // 创建或复用列表项视图 
            if (convertView == null) {
      convertView=LayoutInflater.from(parent.getContext()).inflate(R.layout.list_item_layout, parent, false); 
        } 
            // 获取当前位置的数据项 
            String item = (String) getItem(position); // 在列表项视图中显示数据                     
            TextView textView = convertView.findViewById(R.id.text_view); 
            textView.setText(item); 
            return convertView; 
        } 
    }
    1.  In the above example, we created a custom adapter MyAdapterthat contains the necessary methods:
      • getCount(): Returns the number of data items.
      • getItem(): Returns the data item at the corresponding position.
      • getItemId(): Returns the ID of the data item. This ID can be used to handle click events and other requirements. The position of the data item is usually used as the ID.
      • getView(): Create or reuse a list item view and display data in it.
  3. Set the adapter: Find the corresponding ListView control in the Activity or Fragment and set the adapter to it.
    1.  
      ListView listView = findViewById(R.id.list_view); 
      MyAdapter adapter = new MyAdapter(dataList); // dataList是前面创建的数据源 listView.setAdapter(adapter);
    2. Through the above steps, we have completed the basic use of the adapter, and the data in the data source will be displayed in each list item in the list view.
  4. Data update: If the data source is dynamic and may change over time, the adapter needs to be notified to refresh the list after updating the data.
// 动态更改数据源 
itemList.add(new Item("标题4", "描述4")); 
adapter.notifyDataSetChanged();

5. List view in layout file

In Android layout files, you can use the ListView element to define and configure list views. Here is a simple example to demonstrate how to write a list view in a layout file:

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

    <!-- 其他布局元素 --> 
    <ListView 
        android:id="@+id/listView" 
        android:layout_width="match_parent" 
        android:layout_height="wrap_content" /> 

</LinearLayout>

In the above example, LinearLayout is used as the root layout, which contains other layout elements (can be added according to actual needs) and a ListView element. In the ListView element, you can set the corresponding properties as needed.

Commonly used ListView properties include:

  • android:id: Assign a unique identifier to the ListView.
  • android:layout_widthand android:layout_height: used to set the width and height of ListView.
  • android:dividerand android:dividerHeight: can be used to set the separator line between list items and their height.
  • android:listSelector: Used to set the background color or style when a list item is selected.
  • android:scrollbars: Can be used to set the display mode of the scroll bar.

In addition to the ListView element itself, an adapter (Adapter) is also needed to provide data for the list. The adapter is responsible for associating data with the list view so that the data can be displayed correctly in the list. Specific adapter configuration and data binding operations are usually completed in Java code.

It should be noted that starting from Android 10 (API level 29), Google recommends using  RecyclerView  as a more flexible and efficient list view component. RecyclerView provides more features and optimization options and can replace the traditional ListView. If the minimum supported version of your application's target device is higher than Android 10, it is recommended to use RecyclerView instead of ListView.

6. Customize list item layout

Customizing the list item layout is done by creating an XML file to define the appearance and layout of the list item view. Here's a simple example showing how to create a custom list item layout:

  1. Create a new XML file:res/layout Create a new XML file in the directory of the Android project and name it list_item_layout.xml(you can name it according to actual needs).

  2. Define the list item layout: In list_item_layout.xmlthe file, use various layouts and controls to define the appearance of the list items. Here is an example that contains a TextView as the display content of a list item:

<!-- list_item_layout.xml --> 
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"             
    android:layout_width="match_parent" 
    android:layout_height="wrap_content" 
    android:orientation="vertical" 
    android:padding="8dp"> 
        <TextView 
            android:id="@+id/text_view" 
            android:layout_width="match_parent" 
            android:layout_height="wrap_content" 
            android:textSize="16sp" 
            android:textColor="@android:color/black" /> 
</LinearLayout>

In the above example, we use a LinearLayout as a container, which contains a TextView to display the text content of the list items. You can add more layouts and controls as needed to achieve different styles and interactive effects.

     3. Use a custom layout in the adapter: In the adapter's getView()method, load the custom layout file as a view, and populate and set data as needed.

@Override public View getView(int position, View convertView, ViewGroup parent) { 
    // 创建或复用列表项视图 
    if (convertView == null) { 
           convertView=
                LayoutInflater.from(parent.getContext()).inflate(R.layout.list_item_layout, parent, false); 
} 
    // 获取当前位置的数据项 
    String item = (String) getItem(position); 
    // 在列表项视图中显示数据 
    TextView textView = convertView.findViewById(R.id.text_view); 
    textView.setText(item); 
    return convertView; 
}

In the above code, we use LayoutInflaterthe inflate()method to load the custom list item layout file as a view, and findViewById()find the TextView control in it through the method. We can then setText()set the data from the adapter into the TextView via methods.

After completing the above steps, you have successfully created a custom list item layout and used it in the adapter to display the content of the list items.

7. List item click event processing

To handle click events for a list item, you can set a click listener for the list item in the adapter . Here's an example that shows how to handle a list item's click event in an adapter:

       getView()1. Set a click listener for the list item in the adapter method:

@Override 
public View getView(final int position, View convertView, ViewGroup parent) { // 创建或复用列表项视图 
    if (convertView == null) { 
        convertView = LayoutInflater.from(parent.getContext()).inflate(R.layout.list_item_layout, parent, false); 
} 
    // 获取当前位置的数据项 
    String item = (String) getItem(position); 
    // 在列表项视图中显示数据 
    TextView textView = convertView.findViewById(R.id.text_view); textView.setText(item); 
    // 设置点击监听器 
    convertView.setOnClickListener(new View.OnClickListener() { 
        @Override 
        public void onClick(View v) { // 处理列表项点击事件 
            // 在这里编写点击事件处理的代码 
            // 可以使用position参数获取当前点击的列表项位置 
        } 
    }); 
    return convertView; 
}
In the above code, we convertViewset up a click listener on (the list item view) and onClick()wrote the code to handle the click event in the method. You can write the click logic for the list items in the adapter here if needed.

Note that we use positionparameters to get the position of the currently clicked list item. This can help you identify which list item the user clicked on and act accordingly .

        2. Add click event processing logic: Add specific click event processing logic to onClick()the method in the adapter. For example, you can open a new Activity or Fragment to display detailed information, or perform other operations.

convertView.setOnClickListener(new View.OnClickListener() { 
    @Override 
    public void onClick(View v) { // 处理列表项点击事件 
        // 在这里编写点击事件处理的代码 
        // 可以使用position参数获取当前点击的列表项位置 
        // 例如,打开新的Activity并传递数据 
        String selectedItem = (String) getItem(position); 
        Intent intent = new Intent(v.getContext(), DetailActivity.class);             
        intent.putExtra("selectedItem", selectedItem);     
        v.getContext().startActivity(intent); 
    } 
});

In the above example, we obtain the selected data item based on the position of the list item clicked by the user, then create an Intent containing the data and pass it as a parameter to the new Activity (DetailActivity). You can modify and extend it according to your needs.

8. List optimization

Optimizing list views can improve your app's performance and user experience. The following are some common list view-related functions, including how to implement search filtering, pull-down refresh, and sliding menus:

  1. Search filter function:

    • Create a search box (EditText) to receive user input.
    • Listen to the search box text change event and trigger the filtering operation when the text changes.
    • According to the keywords entered by the user, the data source is filtered in the adapter to obtain matching results.
    • Updates the adapter's data set to display only list items that match the search criteria.
  2. Pull-down refresh function:

    • Use SwipeRefreshLayout as the parent container of the list view, which provides the pull-down refresh function.
    • Set the OnRefreshListener listener to trigger the refresh operation when the user pulls down the list.
    • Perform refresh operations in the listener, such as reloading data or performing network requests.
    • When the refresh is completed, call the SwipeRefreshLayout setRefreshing(false)method to end the refresh state.
  3. Side sliding menu function:

    • Use third-party libraries, such as RecyclerView's ItemTouchHelper, to implement the side-sliding menu function.
    • Set the ItemTouchHelper.Callback callback in the adapter to listen for the sliding event of the list item.
    • Handle sliding events in the callback method, such as displaying a delete button or menu option when swiping right.
    • Based on the user's actions, perform corresponding actions, such as deleting list items or displaying more options.

In addition to the above features, you can also consider the following optimization measures to improve the performance and user experience of list views:

  • Use ViewHolder mode: Use ViewHolder in the adapter to reuse views, reduce the cost of view creation, and improve the smoothness of scrolling.
  • Paging loading: When there are many list items, paging loading can be used to load data on demand to avoid lagging caused by loading a large amount of data at once.
  • Image loading optimization: Use an image loading library (such as Glide or Picasso) to load and cache images asynchronously to avoid performing time-consuming operations on the main thread.

10. Sample code and demonstration

Here we mainly parse three lists:

  • Simple list--ArrayAdapter
  • Picture and text list--SimpleAdapter
  • Complex list of graphics and text--BaseAdapter ( key point )

[Demonstration effect] :

ListView application

  [Core code] :

1. ItemBean class

Create a bena package, create an ItemBean class in this package directory, and define the article title, content, and pictures

public class ItemBean implements Serializable {

    private String title; // 标题
    private String content; // 内容
    private int imgResId; // 图片


    public String getTitle() {
        return title;
    }

    public void setTitle(String title) {
        this.title = title;
    }

    public String getContent() {
        return content;
    }

    public void setContent(String content) {
        this.content = content;
    }

    public int getImgResId() {
        return imgResId;
    }

    public void setImgResId(int imgResId) {
        this.imgResId = imgResId;
    }

    @Override
    public String toString() {
        return "ItemBean{" +
                "title='" + title + '\'' +
                ", content='" + content + '\'' +
                ", imgResId=" + imgResId +
                '}';
    }
}

2.Home Button button

Edit the following code in the activity_main.xml file:

<?xml version="1.0" encoding="utf-8"?>
<ScrollView 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"
    android:orientation="vertical"
    tools:context=".MainActivity">


    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_marginRight="10dp"
        android:orientation="vertical"
        android:paddingLeft="10dp">

        <Button
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_marginTop="10dp"
            android:text="Array列表"
            android:onClick="toArrayListTest"
            android:textAllCaps="false" />

        <Button
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_marginTop="10dp"
            android:text="simple列表"
            android:onClick="toSimpleListTest"
            android:textAllCaps="false" />

        <Button
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_marginTop="10dp"
            android:text="BaseAdapter列表"
            android:onClick="toBaseListTest"
            android:textAllCaps="false" />

        <Button
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_marginTop="10dp"
            android:text="FensiList列表"
            android:onClick="toFrensiListActivity"
            android:textAllCaps="false" />
    </LinearLayout>
</ScrollView>

 [Page effect]:

[Figure 2 activity_main.xml rendering]

3. Add a click event in the main program class to jump to the corresponding list view

        (1) Create 5 empty activities and name them respectively:

[Figure 3 Activity Catalog Diagram]

         (2) Add a click event to the MainActivty main program class and jump to the corresponding list view

 public void toArrayListTest(View view) {
        Intent intent = new Intent(this, ArrayListActivity.class);
        startActivity(intent);
    }

    public void toSimpleListTest(View view) {
        Intent intent = new Intent(this, SimpleListActivity.class);
        startActivity(intent);
    }

    public void toBaseListTest(View view) {
        Intent intent = new Intent(this, BaseAdapterActivity.class);
        startActivity(intent);
    }

    public void toFrensiListActivity(View view) {
        Intent intent = new Intent(this, FensiListActivity.class);
        startActivity(intent);
    }

         (3) Define the ListView view in the three files activity_array_list.xml, activity_base_adapter.xml, and activity_simple_list.xml in the res/layout directory

<?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"
    android:orientation="vertical"
    tools:context=".BaseAdapterActivity">

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

</LinearLayout>

        (4) Create a new xml file in the res/layout directory and name it list_item_layout.xml 

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingLeft="10dp"
    android:paddingTop="5dp"
    android:paddingRight="10dp"
    android:paddingBottom="5dp">

    <ImageView
        android:id="@+id/iv_img"
        android:layout_width="100dp"
        android:layout_height="100dp"
        android:scaleType="centerCrop"
        android:src="@drawable/ic_launcher_background" />

    <TextView
        android:id="@+id/tv_title"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginLeft="10dp"
        android:layout_toRightOf="@id/iv_img"
        android:ellipsize="end"
        android:maxLines="1"
        android:text="雨中漫步"
        android:textSize="20sp"
        android:textStyle="bold" />

    <TextView
        android:id="@+id/tv_content"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_below="@id/tv_title"
        android:layout_marginLeft="10dp"
        android:layout_toRightOf="@id/iv_img"
        android:ellipsize="end"
        android:maxLines="3"
        android:text="人生就像一场旅行,不必在乎目的地,在乎的是沿途的风景以及看风景的心情,让心灵去旅行"
        android:textSize="16sp" />
</RelativeLayout>

【Rendering】:

  [Figure 4 Customized list items]

 4. Simple list--ArrayAdapter

        ( 1) Create a new adapter package, and create a new MyAdapter adapter in this package directory   , which is used for the ArrayListActivity activity.

public class MyAdapter extends BaseAdapter {

    private List<ItemBean> mBeanList;
    private LayoutInflater mLayoutInflater;
    private Context mContext;

    public MyAdapter(Context context,List<ItemBean> beanList){
        this.mContext = context;
        this.mBeanList = beanList;
        mLayoutInflater = LayoutInflater.from(mContext);
    }

    @Override
    public int getCount() {
        return mBeanList.size();
    }

    @Override
    public Object getItem(int position) {
        return mBeanList.get(position);
    }

    @Override
    public long getItemId(int position) {
        return position;
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        // 创建视图控件
        convertView = mLayoutInflater.inflate(R.layout.list_item_layout, parent, false);
        ImageView imageView = convertView.findViewById(R.id.iv_img);
        TextView tvTitle = convertView.findViewById(R.id.tv_title);
        TextView tvContent = convertView.findViewById(R.id.tv_content);

        // 为控件填充数据
        ItemBean itemBean = mBeanList.get(position);
        imageView.setImageResource(itemBean.getImgResId());
        tvTitle.setText(itemBean.getTitle());
        tvContent.setText(itemBean.getContent());

        return convertView;
    }
}

Code analysis:

        The MyAdapter class here inherits from BaseAdapter and implements several of its methods. We can customize the layout and style of the list items by populating the subview's data for each list item in the getView() method.

In the getView() method, first check whether convertView is empty. If it is empty, use LayoutInflater to R.layout.list_item_layoutcreate a new view from the layout file. Then, obtain the controls in the subview layout through the findViewById() method, and bind these controls to the data in the data source.

        Among them, ItemBean is a custom data model class used to store the data of each list item. Obtain the ItemBean object at the corresponding position by calling the getItem() method, and then use the method of the object to obtain the corresponding data and set it to the subview control.

        Finally, the view object filled with data is returned for ListView to display.

          (2).Edit the ArrayListActivity class

public class ArrayListActivity extends AppCompatActivity {

    private ListView mListView;
    private List<String> mStringList;
    private ArrayAdapter<String> mArrayAdapter;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_array_list);
        mListView = findViewById(R.id.lv);
        mStringList = new ArrayList<>();

        for (int i = 0; i < 50; i++) {
            mStringList.add("这是条目" + i);
        }
        mArrayAdapter = new ArrayAdapter<>(this, android.R.layout.simple_list_item_1, mStringList);

        mListView.setAdapter(mArrayAdapter);
        mListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                Toast.makeText(ArrayListActivity.this,"你点击了"+position,Toast.LENGTH_SHORT).show();
            }
        });


        mListView.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
            @Override
            public boolean onItemLongClick(AdapterView<?> parent, View view, int position, long id) {
                Toast.makeText(ArrayListActivity.this,"你长按了"+position,Toast.LENGTH_SHORT).show();

                return true;
            }
        });
    }
}

Code analysis: 

        In the onCreate() method, first set the layout file to activity_array_list.xml through the setContentView() method. Then, use the findViewById() method to obtain an instance of the ListView control.

        Next, we created an ArrayList object as the data source and added 50 entry strings to it using a for loop. Then, create an ArrayAdapter object, associate it with the data source, and set the adapter to the ListView control to display the data.

        At the same time, we also set up click event and long press event listeners for the list items. When the user clicks on the list item, a Toast prompt box will pop up to display the current clicked position. When the user long-presses a list item, a Toast prompt box will also pop up to display the current long-pressed position.

        In this way, the ArrayListActivity class completes a simple list display based on ArrayList, and provides corresponding processing logic for click events and long press events of list items.

5. Picture and text list--SimpleAdapter

        (1) SimplListActivity activity adapter  MyAdapter2 

Because when using the ListView adapter, convertView is usually used to reuse views. There may be cases where convertView is empty, indicating that there is currently no reusable view.

Therefore, based on the MyAdapter class, we change part of the code that creates the view control in the getView() method,

Determine whether convertView is empty. If convertView is empty, it means that there is currently no reusable view and a new view needs to be created.

// 创建视图控件
        if (convertView == null) {
            convertView = mLayoutInflater.inflate(R.layout.list_item_layout, parent, false);
        }

        (2) SimpleListActivity 类

public class SimpleListActivity extends AppCompatActivity {

    private ListView mListView;
    private SimpleAdapter mSimpleAdapter;
    private List<Map<String, Object>> mList;

    private int[] imgs = {
            R.drawable.test1,
            R.drawable.test2,
            R.drawable.test3,
            R.drawable.test4,
            R.drawable.test5,
            R.drawable.test6,
            R.drawable.test7,
            R.drawable.test8,
            R.drawable.test9
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_simple_list);
        mListView = findViewById(R.id.lv);

        mList = new ArrayList<>();

        for (int i = 0; i < 50; i++) {
            Map<String, Object> map = new HashMap();
            map.put("img", imgs[i % imgs.length]);
            map.put("title", "这是标题" + i);
            map.put("content", "这是内容" + i);

            mList.add(map);
        }

        mSimpleAdapter = new SimpleAdapter(this,
                mList,
                R.layout.list_item_layout,
                new String[]{"img", "title", "content"},
                new int[]{R.id.iv_img, R.id.tv_title, R.id.tv_content}
        );

        mListView.setAdapter(mSimpleAdapter);
        mListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                Map<String, Object> map = mList.get(position);
                String title = (String) map.get("title");
                Toast.makeText(SimpleListActivity.this, "你点击了" + position + title, Toast.LENGTH_SHORT).show();

            }
        });

    }
}

 Code analysis:

        In the onCreate() method, first set the layout file to activity_simple_list.xml through the setContentView() method. Then use the findViewById() method to obtain an instance of the ListView control.

        Next, we create an ArrayList object as the data source mList and add 50 entries to it using a loop. Each entry is a HashMap object, which contains information such as pictures, titles, and content.

Then, a SimpleAdapter object mSimpleAdapter is created and associated with the data source mList. When constructing the SimpleAdapter object, we specify the layout file list_item_layout.xml of the list item, as well as the keys corresponding to each data in the data source mList and the control ID in the list item layout.

        Finally, set the SimpleAdapter to the ListView control to display the data. At the same time, we also set up a click event listener for the list item. When the user clicks on a list item, the data item at the current clicked position will be obtained through the getItem() method, and then the title information will be taken out and a Toast prompt box will pop up to display the currently clicked position and title.

        In this way, the SimpleListActivity class completes a simple list display based on SimpleAdapter and provides corresponding processing logic for the click event of the list item.

6. Complex list of graphics and text--BaseAdapter ( key point )

        (1) BaseAdapterActivity activity adapter MyAdapter3

  @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        // 创建视图控件
        ViewHolder viewHolder = new ViewHolder();
        if (convertView == null) {
            convertView = mLayoutInflater.inflate(R.layout.list_item_layout, parent, false);
            ImageView imageView = convertView.findViewById(R.id.iv_img);
            TextView tvTitle = convertView.findViewById(R.id.tv_title);
            TextView tvContent = convertView.findViewById(R.id.tv_content);
            viewHolder.imageView = imageView;
            viewHolder.tvTitle = tvTitle;
            viewHolder.tvContent = tvContent;
            convertView.setTag(viewHolder);
        } else {
            viewHolder = (ViewHolder) convertView.getTag();
        }

        // 为控件填充数据
        ItemBean itemBean = mBeanList.get(position);
        viewHolder.imageView.setImageResource(itemBean.getImgResId());
        viewHolder.tvTitle.setText(itemBean.getTitle());
        viewHolder.tvContent.setText(itemBean.getContent());

        return convertView;
    }

    class ViewHolder {
        ImageView imageView;
        TextView tvTitle;
        TextView tvContent;
    }

  Code analysis:

        In the getView() method, an internal class named ViewHolder is first created to store each control instance in the list item layout.

        Then, under the condition of judging whether convertView is empty, two branch operations are performed:

  •  When convertView is empty, it means that the current list item needs to be created. Convert the layout file list_item_layout.xml into a View object through the inflate() method of LayoutInflater, and find the ImageView and TextView controls in it. Assign their instances to the corresponding member variables of ViewHolder, and attach the ViewHolder object to the convertView through the setTag() method so that it can be retrieved later using the getTag() method.
  • When convertView is not empty, it means that the current list item can be reused. Directly use the getTag() method to retrieve the previously stored ViewHolder object from convertView.

        When filling data into the control in ViewHolder, obtain the ItemBean object at the current location through the getItem() method, and retrieve the image resource ID, title and content information from it. Then, set these information to the corresponding controls in the ViewHolder respectively, completing the data filling.

        Finally, the convertView filled with data is returned for display in the list.

In this way, the getView() method is rewritten in the SimpleAdapter to realize the dynamic creation and reuse of the list item layout, and correctly fill the data into the control, so that the list can display the data correctly. At the same time, using ViewHolder mode can improve the scrolling performance of the list.

         (2) Edit the activity_news_detail.xml file

<?xml version="1.0" encoding="utf-8"?>
<ScrollView 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"
    android:orientation="vertical">

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:orientation="vertical"
        android:paddingLeft="10dp"
        android:paddingRight="10dp"
        tools:context=".NewsDetailActivity">

        <TextView
            android:id="@+id/tv_title"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_marginTop="10dp"
            android:gravity="center"
            android:text="林间漫步"
            android:textSize="25sp"
            android:textStyle="bold" />

        <ImageView
            android:id="@+id/iv_img"
            android:layout_width="400dp"
            android:layout_height="300dp"
            android:layout_marginTop="10dp"
            android:scaleType="centerCrop"
            android:src="@color/colorPrimaryDark" />

        <TextView
            android:id="@+id/tv_content"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_marginTop="10dp"
            android:layout_marginBottom="40dp"
            android:gravity="start|left"
            android:text="一根线如果绷得太紧,总有一天会断裂,一颗心若是禁锢得太久,总有一天会失去平衡,我们需要放飞心灵,让心翱翔在自由的太空。"
            android:textSize="16sp"

            />

    </LinearLayout>
</ScrollView>

[Rendering]:

 [Figure 5 activity_news_detail.xml rendering]

 

         (3)  NewsDetailActivity 类

package com.sziiit.listview_demo1;

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

import androidx.appcompat.app.AppCompatActivity;

import com.sziiit.listview_demo1.adapter.MyAdapter3;
import com.sziiit.listview_demo1.bean.ItemBean;

import java.util.ArrayList;
import java.util.List;

public class BaseAdapterActivity extends AppCompatActivity {

    private ListView mListView;
    private List<ItemBean> mBeanList;
    private MyAdapter3 mMyAdapter;


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

        initView();
        initData();
        initEvent();
    }

    private void initEvent() {
        mMyAdapter = new MyAdapter3(this,mBeanList);
        mListView.setAdapter(mMyAdapter);
        mListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                ItemBean itemBean = mBeanList.get(position);
                String title = itemBean.getTitle();
                Intent intent = new Intent(BaseAdapterActivity.this, NewsDetailActivity.class);
                intent.putExtra("item",itemBean);
                startActivity(intent);

                Toast.makeText(BaseAdapterActivity.this, "你点击了" + position + title, Toast.LENGTH_SHORT).show();
            }
        });
        mListView.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
            @Override
            public boolean onItemLongClick(AdapterView<?> parent, View view, int position, long id) {

                return false;
            }
        });
    }

    private void initData() {
        mBeanList = new ArrayList<>();

        ItemBean newsBean1 = new ItemBean();
        newsBean1.setTitle("雨中漫步");
        newsBean1.setContent("人生就像一场旅行,不必在乎目的地,在乎的是沿途的风景以及看风景的心情,让心灵去旅行。\n只想进行一场漫无目的的旅行,在一个有花有海、安静缓慢的地方晒着太阳无所事事。\n背着背包的路上,看过许多人,听过许多故事,见过旅行风景,就这样,慢慢学会了长大。");
        newsBean1.setImgResId(R.drawable.test1);

        ItemBean newsBean2 = new ItemBean();
        newsBean2.setTitle("林间穿梭");
        newsBean2.setContent("只想进行一场漫无目的的旅行,在一个有花有海、安静缓慢的地方晒着太阳无所事事。\n路旁边浪似地滚着高高低低的黄土。太阳给埋在黄土里,发着肉红色。可是太阳还烧得怪起劲的,把他们的皮肉烧得变成紫黑色,似乎还闻得到一股焦味儿。");
        newsBean2.setImgResId(R.drawable.test2);

        ItemBean newsBean3 = new ItemBean();
        newsBean3.setTitle("旅行花海");
        newsBean3.setContent("只想进行一场漫无目的的旅行,在一个有花有海、安静缓慢的地方晒着太阳无所事事。\n背着背包的路上,看过许多人,听过许多故事,见过旅行风景,就这样,慢慢学会了长大。\n" +
                "\n" +
                "想呼吸着每座城市的空气,想感受着每座城市的人儿,想看着每座城市的风景。");
        newsBean3.setImgResId(R.drawable.test3);


        ItemBean newsBean4 = new ItemBean();
        newsBean4.setTitle("非平衡的线");
        newsBean4.setContent("一根线如果绷得太紧,总有一天会断裂,一颗心若是禁锢得太久,总有一天会失去平衡,我们需要放飞心灵,让心翱翔在自由的太空。每个人在他的人生发轫之初,总有一段时光,没有什么可留恋,只有抑制不住的梦想,没有什么可凭仗,只有他的好身体,没有地方可去,只想到处流浪。");
        newsBean4.setImgResId(R.drawable.test4);

        ItemBean newsBean5 = new ItemBean();
        newsBean5.setTitle("说走就走");
        newsBean5.setContent("说走就走的旅行,要么缘由幸福稳定和宽裕,要么祸起无力无奈和逃避。\n在旅途中,我遇见了你,你我相识是缘分!看着你手中的戒指,你说,你可以把它取下来吗?当我要取的时候,你淘气的躲开了,你说只有有缘人才可以取下,我看着你手中的戒指,想做你的有缘人,可是我知道结果是惨淡的,但还是心存希望!");
        newsBean5.setImgResId(R.drawable.test5);

        ItemBean newsBean6 = new ItemBean();
        newsBean6.setTitle("美好的记忆");
        newsBean6.setContent("旅行不在乎终点,而是在意途中的人和事还有那些美好的记忆和景色。人生就是一次充满未知的旅行,在乎的是沿途的风景,在乎的是看风景的心情,旅行不会因为美丽的风景终止。走过的路成为背后的风景,不能回头不能停留,若此刻停留,将会错过更好的风景,保持一份平和,保持一份清醒。享受每一刻的感觉,欣赏每一处的风景,这就是人生。(作者:《遇到另一种生活》");
        newsBean6.setImgResId(R.drawable.test6);

        ItemBean newsBean7 = new ItemBean();
        newsBean7.setTitle("久违的感动");
        newsBean7.setContent("人生最好的旅行,就是你在一个陌生的地方,发现一种久违的感动。人生最好的旅行,就是你在一个陌生的地方,发现一种久违的感动");
        newsBean7.setImgResId(R.drawable.test7);

        ItemBean newsBean8 = new ItemBean();
        newsBean8.setTitle("流浪日记");
        newsBean8.setContent("着背包的路上,看过许多人,听过许多故事,见过旅行风景,就这样,慢慢学会了长大。\n每个人在他的人生发轫之初,总有一段时光,没有什么可留恋,只有抑制不住的梦想,没有什么可凭仗,只有他的好身体,没有地方可去,只想到处流浪。");
        newsBean8.setImgResId(R.drawable.test8);

        ItemBean newsBean9 = new ItemBean();
        newsBean9.setTitle("山的尽头");
        newsBean9.setContent("在向山靠近一点,才发现这座山,好象一位诗人遥望远方,等待故人的归来。山上的树,大多数是松树比较突出。松树亭亭玉立的耸立在周围小草小花的中间,仿佛松树就是一位威风的将军,守护着国家的国民。\n在向山靠近一点,才发现这座山,好象一位诗人遥望远方,等待故人的归来。山上的树,大多数是松树比较突出。松树亭亭玉立的耸立在周围小草小花的中间,仿佛松树就是一位威风的将军,守护着国家的国民。\n在向山靠近一点,才发现这座山,好象一位诗人遥望远方,等待故人的归来。山上的树,大多数是松树比较突出。松树亭亭玉立的耸立在周围小草小花的中间,仿佛松树就是一位威风的将军,守护着国家的国民。");
        newsBean9.setImgResId(R.drawable.test9);

        ItemBean newsBean10 = new ItemBean();
        newsBean10.setTitle("秦河魅影");
        newsBean10.setContent("秦淮河、夫子庙,繁华依旧,只少了些当年桨声灯影的风味。喝一碗鸭血粉丝,吃一客蟹黄汤包,坐一次龙舟游船,览一河别样风景,发一回思古幽情,我想,这也许就是所谓夜游秦淮的小资情调了。独游,却只有看客的心情。\n秦淮河、夫子庙,繁华依旧,只少了些当年桨声灯影的风味。喝一碗鸭血粉丝,吃一客蟹黄汤包,坐一次龙舟游船,览一河别样风景,发一回思古幽情,我想,这也许就是所谓夜游秦淮的小资情调了。独游,却只有看客的心情。\n秦淮河、夫子庙,繁华依旧,只少了些当年桨声灯影的风味。喝一碗鸭血粉丝,吃一客蟹黄汤包,坐一次龙舟游船,览一河别样风景,发一回思古幽情,我想,这也许就是所谓夜游秦淮的小资情调了。独游,却只有看客的心情。");
        newsBean10.setImgResId(R.drawable.test10);

        mBeanList.add(newsBean1);
        mBeanList.add(newsBean2);
        mBeanList.add(newsBean3);
        mBeanList.add(newsBean4);
        mBeanList.add(newsBean5);
        mBeanList.add(newsBean6);
        mBeanList.add(newsBean7);
        mBeanList.add(newsBean8);
        mBeanList.add(newsBean9);
        mBeanList.add(newsBean10);
        mBeanList.add(newsBean1);
        mBeanList.add(newsBean2);
        mBeanList.add(newsBean3);
        mBeanList.add(newsBean4);
        mBeanList.add(newsBean5);
        mBeanList.add(newsBean6);
        mBeanList.add(newsBean7);
        mBeanList.add(newsBean8);
        mBeanList.add(newsBean9);
        mBeanList.add(newsBean10);
    }

    private void initView() {
        mListView = findViewById(R.id.lv);
    }
}

         (4) BaseAdapterActivity class

public class BaseAdapterActivity extends AppCompatActivity {

    private ListView mListView;
    private List<ItemBean> mBeanList;
    private MyAdapter3 mMyAdapter;


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

        initView();
        initData();
        initEvent();
    }

    private void initEvent() {
        mMyAdapter = new MyAdapter3(this,mBeanList);
        mListView.setAdapter(mMyAdapter);
        mListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                ItemBean itemBean = mBeanList.get(position);
                String title = itemBean.getTitle();
                Intent intent = new Intent(BaseAdapterActivity.this, NewsDetailActivity.class);
                intent.putExtra("item",itemBean);
                startActivity(intent);

                Toast.makeText(BaseAdapterActivity.this, "你点击了" + position + title, Toast.LENGTH_SHORT).show();
            }
        });
        mListView.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
            @Override
            public boolean onItemLongClick(AdapterView<?> parent, View view, int position, long id) {

                return false;
            }
        });
    }

    private void initData() {
        mBeanList = new ArrayList<>();

        ItemBean newsBean1 = new ItemBean();
        newsBean1.setTitle("雨中漫步");
        newsBean1.setContent("人生就像一场旅行,不必在乎目的地,在乎的是沿途的风景以及看风景的心情,让心灵去旅行。\n只想进行一场漫无目的的旅行,在一个有花有海、安静缓慢的地方晒着太阳无所事事。\n背着背包的路上,看过许多人,听过许多故事,见过旅行风景,就这样,慢慢学会了长大。");
        newsBean1.setImgResId(R.drawable.test1);

        ItemBean newsBean2 = new ItemBean();
        newsBean2.setTitle("林间穿梭");
        newsBean2.setContent("只想进行一场漫无目的的旅行,在一个有花有海、安静缓慢的地方晒着太阳无所事事。\n路旁边浪似地滚着高高低低的黄土。太阳给埋在黄土里,发着肉红色。可是太阳还烧得怪起劲的,把他们的皮肉烧得变成紫黑色,似乎还闻得到一股焦味儿。");
        newsBean2.setImgResId(R.drawable.test2);

        ItemBean newsBean3 = new ItemBean();
        newsBean3.setTitle("旅行花海");
        newsBean3.setContent("只想进行一场漫无目的的旅行,在一个有花有海、安静缓慢的地方晒着太阳无所事事。\n背着背包的路上,看过许多人,听过许多故事,见过旅行风景,就这样,慢慢学会了长大。\n" +
                "\n" +
                "想呼吸着每座城市的空气,想感受着每座城市的人儿,想看着每座城市的风景。");
        newsBean3.setImgResId(R.drawable.test3);


        ItemBean newsBean4 = new ItemBean();
        newsBean4.setTitle("非平衡的线");
        newsBean4.setContent("一根线如果绷得太紧,总有一天会断裂,一颗心若是禁锢得太久,总有一天会失去平衡,我们需要放飞心灵,让心翱翔在自由的太空。每个人在他的人生发轫之初,总有一段时光,没有什么可留恋,只有抑制不住的梦想,没有什么可凭仗,只有他的好身体,没有地方可去,只想到处流浪。");
        newsBean4.setImgResId(R.drawable.test4);

        ItemBean newsBean5 = new ItemBean();
        newsBean5.setTitle("说走就走");
        newsBean5.setContent("说走就走的旅行,要么缘由幸福稳定和宽裕,要么祸起无力无奈和逃避。\n在旅途中,我遇见了你,你我相识是缘分!看着你手中的戒指,你说,你可以把它取下来吗?当我要取的时候,你淘气的躲开了,你说只有有缘人才可以取下,我看着你手中的戒指,想做你的有缘人,可是我知道结果是惨淡的,但还是心存希望!");
        newsBean5.setImgResId(R.drawable.test5);

        ItemBean newsBean6 = new ItemBean();
        newsBean6.setTitle("美好的记忆");
        newsBean6.setContent("旅行不在乎终点,而是在意途中的人和事还有那些美好的记忆和景色。人生就是一次充满未知的旅行,在乎的是沿途的风景,在乎的是看风景的心情,旅行不会因为美丽的风景终止。走过的路成为背后的风景,不能回头不能停留,若此刻停留,将会错过更好的风景,保持一份平和,保持一份清醒。享受每一刻的感觉,欣赏每一处的风景,这就是人生。(作者:《遇到另一种生活》");
        newsBean6.setImgResId(R.drawable.test6);

        ItemBean newsBean7 = new ItemBean();
        newsBean7.setTitle("久违的感动");
        newsBean7.setContent("人生最好的旅行,就是你在一个陌生的地方,发现一种久违的感动。人生最好的旅行,就是你在一个陌生的地方,发现一种久违的感动");
        newsBean7.setImgResId(R.drawable.test7);

        ItemBean newsBean8 = new ItemBean();
        newsBean8.setTitle("流浪日记");
        newsBean8.setContent("着背包的路上,看过许多人,听过许多故事,见过旅行风景,就这样,慢慢学会了长大。\n每个人在他的人生发轫之初,总有一段时光,没有什么可留恋,只有抑制不住的梦想,没有什么可凭仗,只有他的好身体,没有地方可去,只想到处流浪。");
        newsBean8.setImgResId(R.drawable.test8);

        ItemBean newsBean9 = new ItemBean();
        newsBean9.setTitle("山的尽头");
        newsBean9.setContent("在向山靠近一点,才发现这座山,好象一位诗人遥望远方,等待故人的归来。山上的树,大多数是松树比较突出。松树亭亭玉立的耸立在周围小草小花的中间,仿佛松树就是一位威风的将军,守护着国家的国民。\n在向山靠近一点,才发现这座山,好象一位诗人遥望远方,等待故人的归来。山上的树,大多数是松树比较突出。松树亭亭玉立的耸立在周围小草小花的中间,仿佛松树就是一位威风的将军,守护着国家的国民。\n在向山靠近一点,才发现这座山,好象一位诗人遥望远方,等待故人的归来。山上的树,大多数是松树比较突出。松树亭亭玉立的耸立在周围小草小花的中间,仿佛松树就是一位威风的将军,守护着国家的国民。");
        newsBean9.setImgResId(R.drawable.test9);

        ItemBean newsBean10 = new ItemBean();
        newsBean10.setTitle("秦河魅影");
        newsBean10.setContent("秦淮河、夫子庙,繁华依旧,只少了些当年桨声灯影的风味。喝一碗鸭血粉丝,吃一客蟹黄汤包,坐一次龙舟游船,览一河别样风景,发一回思古幽情,我想,这也许就是所谓夜游秦淮的小资情调了。独游,却只有看客的心情。\n秦淮河、夫子庙,繁华依旧,只少了些当年桨声灯影的风味。喝一碗鸭血粉丝,吃一客蟹黄汤包,坐一次龙舟游船,览一河别样风景,发一回思古幽情,我想,这也许就是所谓夜游秦淮的小资情调了。独游,却只有看客的心情。\n秦淮河、夫子庙,繁华依旧,只少了些当年桨声灯影的风味。喝一碗鸭血粉丝,吃一客蟹黄汤包,坐一次龙舟游船,览一河别样风景,发一回思古幽情,我想,这也许就是所谓夜游秦淮的小资情调了。独游,却只有看客的心情。");
        newsBean10.setImgResId(R.drawable.test10);

        mBeanList.add(newsBean1);
        mBeanList.add(newsBean2);
        mBeanList.add(newsBean3);
        mBeanList.add(newsBean4);
        mBeanList.add(newsBean5);
        mBeanList.add(newsBean6);
        mBeanList.add(newsBean7);
        mBeanList.add(newsBean8);
        mBeanList.add(newsBean9);
        mBeanList.add(newsBean10);
        mBeanList.add(newsBean1);
        mBeanList.add(newsBean2);
        mBeanList.add(newsBean3);
        mBeanList.add(newsBean4);
        mBeanList.add(newsBean5);
        mBeanList.add(newsBean6);
        mBeanList.add(newsBean7);
        mBeanList.add(newsBean8);
        mBeanList.add(newsBean9);
        mBeanList.add(newsBean10);
    }

    private void initView() {
        mListView = findViewById(R.id.lv);
    }
}

  Code analysis:

        In onCreatethe method, set up the layout file and initialize the views, data, and event listeners. Then, in initEventthe method, create the adapter MyAdapter3and set it to the ListView, and set click and long press event listeners for the ListView.

The adapter MyAdapter3inherits from BaseAdapter. By rewriting the corresponding method, you can customize the display effect of ListView. Pass in Context and data List<ItemBean> in the constructor for subsequent use. In the getView method, obtain the ItemBean object at the corresponding position according to position, load the layout file through LayoutInflater, fill the data into the corresponding control, and finally return the View.

11. Summary and Outlook

         After learning Android's ListView view list, I have a deeper understanding of the use and management of lists. Through practice and research, I successfully created a list with multiple data items and was able to display related data in the list. I learned to use adapters to connect data and views and bind them to a ListView control. I also learned to handle click events for list items and respond accordingly based on user actions. In addition, I also learned how to optimize the performance of the list and avoid lag problems caused by excessive data volume. By using the ViewHolder pattern and proper memory management, I was able to effectively improve the efficiency of the list.

        In the future, I plan to further explore and apply more advanced features and techniques to expand my knowledge of ListView views. First, I plan to learn how to customize the layout and style of list items to meet different design needs. By using custom layout files and styles, I can add more information and interactive elements to each list item, providing a better user experience. Secondly, I will further research and practice paging loading and asynchronous loading to optimize list display and performance under large data volumes. This will allow the list to load and display large amounts of data quickly, and allow for a smooth scrolling experience. In addition, I also plan to have an in-depth understanding of the use of RecyclerView, which is a more flexible and efficient list control that can meet more complex data display needs. Ultimately, I hope to apply the knowledge and techniques I have learned to actual Android application development to provide users with a better list display and interactive experience.

References:

[1] Lai Hong, Fundamentals of Android Application Development[M.] Beijing: Electronic Industry Press, 2020.3

[2] http://www.android-studio,org/, Android Studio Android developer community.

Guess you like

Origin blog.csdn.net/qq_63559792/article/details/131420612