Android list view

Table of contents

theory:

List View Overview

List View API Documentation

List View Four Elements

 Four Common Adapters

Array Adapter API Documentation

Array adapter constructor

 Parameter description of the fifth construction method

 Specific example: reading ancient poems

Create an Android application based on the Empty Activity template - ReadAncientPoetry

 Copy the background image to the drawable directory

 Open the string resource file strings.xml and enter the code:

Open the main layout resource file activity_main.xml

Create a new poetry list item template poem_list_item.xml and enter the code

 Open the main interface class - MainActivity input code

Start the application to see the effect

Create content interface

Modify the content interface to display the content of ancient poems

Start the application to see the effect:


theory:

List View Overview

The list view (ListView) inherits the abstract list view (AbsListView), which in turn inherits the adapter view (AdapterView). Adapter views have a common feature, which is to use adapters to bind data sources and display controls.

List View API Documentation

https://developer.android.google.cn/reference/android/widget/ArrayAdapter?hl=en

 

List View Four Elements

element illustrate
list control Display multiple options for the user to choose
adapter array adapter, simple adapter, cursor adapter, base adapter
data source Arrays, ArrayLists, Cursors...
list item template Platform resources, user-defined

Four elements of list view: list control, adapter, list item template and data source

 Four Common Adapters

List View (ListView), which is a grandchild of AdapterView, binds the data source through the adapter as a beam bridge

adapter meaning
ArrayAdapter array adapter
SimpleAdapter simple adapter
SimpleCursorAdapter Simple Cursor Adapter
BaseAdapter base adapter

Array Adapter API Documentation

https://developer.android.google.cn/reference/android/widget/ArrayAdapter?hl=en

Array adapter constructor

The array adapter provides 6 overloaded construction methods. We will use the fifth method in the following cases.

 Parameter description of the fifth construction method

 Specific example: reading ancient poems

Create an Android application based on Empty Activitya template - ReadAncientPoetry

 Copy the background image to drawablethe directory

 Open string resource filestrings.xml输入代码:

 Specific code:

<resources> 
    <string name="app_name">Read Ancient Poems</string> 
    <string name="back">Return to Contents</string> 
    <string-array name="titles"> 
        <item>Quiet Night Thoughts</item> 
        <item>Climbing the Stork Tower</item> 
        <item>Acacia</item> 
        <item>Listening to the piano</item> 
        <item>Climbing the Leyouyuan</item> 
        <item>Chaofa Baidicheng</item > 
        <item>Bashan Night Rain</item> 
        <item>Weicheng Song</item> 
        <item>Happy Rain on a Spring Night</item> 
        <item>Liliyuan Shangcao</item> 
        <item>Shower</item > 
    </string-array> 

    <string-array name="authors"> 
        <item>Tang·Li Bai</item> 
        <item>Tang·Wang Zhihuan</item> 
        <item>Tang·Wang Wei</item> 
        <item>Tang·Liu Changqing</item>
        <item>Tang·Li Shangyin</item>Chaoci Baidi among the colorful clouds,\nThousands of miles of Jiangling will be returned in one day. \nThe apes on both sides of the strait can't stop crying,\nThe light boat has passed the Ten Thousand Mountains. 
        </item> <item>There is no deadline for your return, \nBashan night rain rises autumn pond. \n Why cut the candles in the west window together, \n but talk about the night rain in Bashan. </item>
        <item>Tang·Li Bai</item> 
        <item>Tang·Du Mu</item> 
        <item>Tang·Wang Wei</item> <item>Tang·Du Fu 
        </item> 
        <item>Tang·Bai Juyi</item > 
        <item>Song · Lu You</item> 
    </string-array> 

    <string-array name="contents"> 
        <item>There is moonlight in front of the bed,\nsuspected to be frost on the ground. \nLook up at the bright moon,\nLook down and think about your hometown. </item> 
        <item>The sun is at the end of the mountain,\nThe Yellow River flows into the sea. \nIf you want to see a thousand miles,\n go to a higher level. </item> 
        <item>Red beans are born in the southern country,\nSpring comes and sends a few branches. \nMay you pick more,\nThis thing is the most lovesick. </item> 
        <item>Ling Ling Seven Strings,\nListen to the wind and cold in the pine. \nAlthough old tunes are self-love,\nmany people don't play them today. </item> 
        <item>Xiang Wan felt unwell,\ndrive to Guyuan. \nThe setting sun is infinitely good,\nIt's just near dusk. </item> 
        <item>Among the colorful clouds of Baidi Chaoci,\nThousands of miles of Jiangling will be returned in one day. \nThe apes on both sides of the strait can't stop crying,\nThe light boat has passed the Ten Thousand Mountains. </item> 
        <item>The morning rain in Weicheng is light and the dust is light,\nThe guest houses are green and willows are new. \nI advise you to drink more wine, \nThere is no old friend in West Yangguan. </item> 
        <item>Good rain knows the season, when spring happens. \nSneak into the night with the wind, moisten things silently. \nThe wild paths and clouds are all dark, but the river boats and fires are alone. \nXiao Kan red wet place, Hua Chongjin official city. </item> 
        <item>Li Liyuan is on the grass, one year old and one year old. \nThe wild fire is endless, and the spring breeze blows again. \nFar Fang invades the ancient road, and the clear green connects the barren city. \nSend off Wang Sun again, full of love. </item> 
        <item>When you die, you will know everything is empty,\nbut sadly, Kyushu will not be the same. \nWang Shibei set the Central Plains Day, \nFamily sacrifices will never be forgotten to tell Nai Weng. </item> 
    </string-array> 

</resources>

Open the main layout resource fileactivity_main.xml

 Specific code:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="@drawable/background"
    android:padding="15dp"
    tools:context=".MainActivity">

    <ListView
        android:id="@+id/lv_poem_title"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:divider="#aaaaaa"
        android:dividerHeight="0.5dp"
        />


</LinearLayout>

New Poetry List Item Template poem_list_item.xml并输入代码

 

 

Specific code:

<?xml version="1.0" encoding="utf-8"?>
<TextView xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/tv_poem_title"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:gravity="center_vertical"
    android:minHeight="80dp"
    android:textColor="#0000ff"
    android:textSize="25sp" />

 Open the main interface class - MainActivity输入代码

 

 Specific code:

package net.zyt.read_ancient_poetry; 

import androidx.appcompat.app.AppCompatActivity; 

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

public class MainActivity extends AppCompatActivity { 
    private ListView lvPoemTitle;//poetry title list control-display 
    private ArrayAdapter<String> adapter;//array adapter-bridge 
    private String[] titles;//poetry title array - data source 


    @Override 
    protected void onCreate(Bundle savedInstanceState) { 
        super.onCreate(savedInstanceState); 
        //use the layout resource file to set the user interface
        setContentView(R.layout.activity_main); 
        //Get the control instance through the resource identifier 
        lvPoemTitle=findViewById(R.id.lv_poem_title); 

        //Initialize the ancient poem title array as the data source of the list control 
       titles=getResources().getStringArray( R.array.titles); 
        //Add a serial number to the title of the poem 
        for (int i=0; i<titles.length;i++){ 
            titles[i]=(i+1)+"."+titles[i]; 
        } 
        //Create an array adapter as a bridge connecting the list control and the data source 
        adapter=new ArrayAdapter<>( 
                this,//context-current window 
                R.layout.poem_list_item,//list item template-custom layout resource 
                titles// Data source - string data group 
        ); 
        //set adapter for list control 
        lvPoemTitle.setAdapter(adapter); 
        //register item click listener for list control
        lvPoemTitle.setOnItemClickListener(new AdapterView.OnItemClickListener() { 
            @Override 
            public void onItemClick(AdapterView<?> adapterView, View view, int position, long id) { 
                Toast.makeText(MainActivity.this,"You have chosen an ancient poem["+titles [position]+"]",Toast.LENGTH_SHORT).show(); 
           //Create intent to realize jump 
                Intent intent=new Intent(MainActivity.this,ContentActivity.class); 
                //Carry data through intent (selected list item position) 
                intent.putExtra("position",position); 
                //Start the target primary key according to the intent 
                startActivity(intent); 

            } 
        }); 
    } 
}

Start the application to see the effect

 

Create content interface

Create an interface to display the content of ancient poems based on templatesContentActivity

 

Open the interface layout resource filecontent_activity.xml输入代码:

 Specific code:
 

<?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:background="@drawable/background"
    android:paddingRight="10dp"
    android:gravity="center"
    android:orientation="vertical">

    <TextView
        android:id="@+id/tv_title"
        android:layout_width="wrap_content"
        android:layout_height="0dp"
        android:layout_marginTop="30dp"
        android:layout_marginBottom="20dp"
        android:layout_weight="1"
        android:gravity="center_vertical"
        android:textColor="#ff00ff"
        android:textSize="40sp" />

    <TextView
        android:id="@+id/tv_author"
        android:layout_width="wrap_content"
        android:layout_height="0dp"
        android:layout_marginBottom="20dp"
        android:layout_weight="1"
        android:gravity="center_vertical"
        android:textColor="#000000"
        android:textSize="25sp" />

    <TextView
        android:id="@+id/tv_content"
        android:layout_width="wrap_content"
        android:layout_height="0dp"
        android:layout_marginBottom="20dp"
        android:layout_weight="8"
        android:textColor="#0000ff"
        android:textSize="30sp" />

    <Button
        android:id="@+id/btn_back"
        android:layout_width="match_parent"
        android:layout_height="0dp"
        android:layout_weight="1"
        android:onClick="doBack"
        android:text="@string/back"
        android:textSize="20sp" />
</LinearLayout>

Modify the content interface to display the content of ancient poems

Open the content interfaceContentActivity

 

 Specific code:

package net.zyt.read_ancient_poetry; 

import androidx.appcompat.app.AppCompatActivity; 

import android.content.Intent; 
import android.os.Bundle; 
import android.view.View; 
import android.widget.TextView; 

public class ContentActivity extends AppCompatActivity { 
    private TextView tvTitle;//title tag 
    private TextView tvAuthor;//author tag 
    private TextView tvContent;//content tag 
    private String[] titles;//title array 
    private String[] authors;//author array 
    private String[] contents; // Content array 

    @Override 
    protected void onCreate(Bundle savedInstanceState) { 
        super.onCreate(savedInstanceState); 
        //Use the layout resource file to set the user interface
        setContentView(R.layout.activity_content); 
        //Get the control instance through the resource identifier 
        tvTitle=findViewById(R.id.tv_title); 
        tvAuthor=findViewById(R.id.tv_author); 
        tvContent=findViewById(R.id.tv_content) ; 
        //Get the intent of window jump 
        Intent intent=getIntent(); 
        //Judge whether the intent is empty 
        if (intent!=null){ 
            //Get the data carried by the intent 
            int position=intent.getIntExtra("position",0) ; 
            //Get an array of ancient poem titles 
            titles=getResources().getStringArray(R.array.titles); 
            //Get an array of ancient poem authors 
            authors=getResources().getStringArray(R.array.authors); 
            //Get ancient poem content tags 
            contents=getResources().getStringArray (R. array. contents); 
            //Set the title label text 
            tvTitle.setText(titles[position]); 
            //Set the author label text 
            tvAuthor.setText(authors[position]); 
            //Set Content label text 
            tvContent.setText(contents[position]); 

        } 
    } 
    public void doBack(View view){ 
        finish();//Close the current window 
    } 
}

Start the application to see the effect:

Guess you like

Origin blog.csdn.net/hollow_future/article/details/127970655