Andriod programming – Posts 11: ListView trong Android

Too 2 all previous theories sure you have an overview over, Today we return to the code with all ListView.
ListView like its name, List is a list, View is displayed, ie the display list. If you've used an Android phone, you will see it everywhere, from contacts, Friends List, list of chat,… ListView are both.

[qads]

In this article, I will guide you to create the most simple ListView, ListView going to post the following complex. First we create the app includes a list of lessons that we have learned as follows:

android-listview-3

The project you created offline With Empty Activity.

How to 1: Create a list of arrays

First we design interfaces. The interface is very simple ListView, we just have objects ListView is finished.

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout 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:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context="com.nguyenvanquan7826.tut11listview.MainActivity">

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

When you set id for ListView, we will look at the following interface:
android-listview-1

In the view on, each item is 1 ListView element when running, here they just describe for us that will show such ListView, but actually we do not have data about the elements in the list offline.

Next, you open the file res / values ​​/ out and add the following string.xml:

<resources>
    <string name="app_name">TUT11ListView</string>

    <string-array name="tut_android">
        <item>Bài 1: Hello World</item>
        <item>Bài 2: TextView, EditText, Button</item>
        <item>Bài 3: Bắt sự kiện click Button</item>
        <item>Bài 4: Thiết kế giao diện với RelativeLayout</item>
        <item>Bài 5: Thiết kế giao diện với LinearLayoout</item>
        <item>Bài 6: Thực hành xây dựng ứng dụng Calculator</item>
        <item>Bài 7: Toast, CheckBox, RadioButton, Dialog</item>
        <item>Bài 8: Intent – Chuyển đổi giữa các màn hình</item>
        <item>Bài 9: Cấu trúc Project</item>
        <item>Bài 10: Vòng đời Activity</item>
    </string-array>
</resources>

Here is, card string-array the card allows contains a list of strings, each placed in a card chain item.

Now is the time to put java code data displayed on the ListView.

package com.nguyenvanquan7826.tut11listview;

import android.content.Context;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.widget.ArrayAdapter;
import android.widget.ListView;

public class MainActivity extends AppCompatActivity {

    private ListView lvTut;
    private String[] listData;
    private ArrayAdapter<String> adapter;

    private Context context;

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

        context = this;

        connectView();
        loadData();
    }

    private void connectView() {
        lvTut = (ListView) findViewById(R.id.lvTUT);
    }

    private void loadData() {
        // get data (string array) from xml file
        listData = context.getResources().getStringArray(R.array.tut_android);

        // create adapter with listData and layout item
        adapter = new ArrayAdapter<>(context, android.R.layout.simple_list_item_1, listData);

        lvTut.setAdapter(adapter);
    }
}

In the code above, you notice the line created adapter, we have 3 argument is Context (context), layout, and listData. In which the layout is android.R.layout.simple_list_item_1 is a file system-available to display 1 Text and we used it for the simple list.

Line taken from the xml file string array will return to us a String[], so in addition to the given string into xml file, we can directly assign string array here, and we can write the following:

private void loadData() {
    listData = new String[] {
            "Bài 1: Hello World",
            "Bài 2: TextView, EditText, Button",
            "Bài 3: Bắt sự kiện click Button"
    };

    // create adapter with listData and layout item
    adapter = new ArrayAdapter<>(context, android.R.layout.simple_list_item_1, listData);

    lvTut.setAdapter(adapter);
}

How to 2: Create playlists from ArrayList

ArrayList is a component we use the most with ListView especially when our list is always changing. The following code illustrates how to use ArrayList.

package com.nguyenvanquan7826.tut11listview;

import android.content.Context;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.widget.ArrayAdapter;
import android.widget.ListView;

import java.util.ArrayList;

public class MainActivity extends AppCompatActivity {

    private ListView lvTut;
    private ArrayList<String> listData;
    private ArrayAdapter<String> adapter;

    private Context context;

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

        context = this;

        connectView();
        loadData();
    }

    private void connectView() {
        lvTut = (ListView) findViewById(R.id.lvTUT);
    }

    private void loadData() {

        listData = new ArrayList<>();
        listData.add("Bài 1: Hello World");
        listData.add("Bài 2: TextView, EditText, Button");
        listData.add("Bài 3: Bắt sự kiện click Button");
        listData.add("Bài 4: Thiết kế giao diện với RelativeLayout");
        listData.add("Bài 5: Thiết kế giao diện với LinearLayoout");

        // create adapter with listData and layout item
        adapter = new ArrayAdapter<>(context, android.R.layout.simple_list_item_1, listData);

        lvTut.setAdapter(adapter);
    }

}

The results you get will not be different from the array made of all. But here I want to mention to you the flexibility to add or remove elements from the list. To accomplish this you continue to edit interface as later.

android-listview-add-item

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout 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:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context="com.nguyenvanquan7826.tut11listview.MainActivity">

    <EditText
        android:id="@+id/editTut"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_toLeftOf="@+id/btnAdd"
        android:hint="Enter tut title" />

    <Button
        android:id="@+id/btnAdd"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentRight="true"
        android:text="Add" />


    <ListView
        android:id="@+id/lvTUT"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_below="@+id/btnAdd" />
</RelativeLayout>

When you click the Add button, we do add to the list.

package com.nguyenvanquan7826.tut11listview;

import android.content.Context;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.text.TextUtils;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.Toast;

import java.util.ArrayList;

public class MainActivity extends AppCompatActivity {

    private ListView lvTut;
    private ArrayList<String> listData;
    private ArrayAdapter<String> adapter;
    
    private EditText editTut;

    private Context context;

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

        context = this;

        connectView();
        loadData();
    }

    private void connectView() {
        lvTut = (ListView) findViewById(R.id.lvTUT);
        editTut = (EditText) findViewById(R.id.editTut);
        findViewById(R.id.btnAdd).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                addTut();
            }
        });
    }

    private void loadData() {

        listData = new ArrayList<>();
        listData.add("Bài 1: Hello World");
        listData.add("Bài 2: TextView, EditText, Button");
        listData.add("Bài 3: Bắt sự kiện click Button");
        listData.add("Bài 4: Thiết kế giao diện với RelativeLayout");
        listData.add("Bài 5: Thiết kế giao diện với LinearLayoout");

        // create adapter with listData and layout item
        adapter = new ArrayAdapter<>(context, android.R.layout.simple_list_item_1, listData);

        lvTut.setAdapter(adapter);
    }
    
    private void addTut(){
        String tut = editTut.getText().toString().trim();
        
        if(TextUtils.isEmpty(tut)) {
            Toast.makeText(context, "Please enter tut title", Toast.LENGTH_SHORT).show();
            return;
        }
        
        listData.add(tut);
        
        // update data to show on listview
        adapter.notifyDataSetChanged();
        
    }

}

In the code above commands your attention adapter.notifyDataSetChanged();, we call it every time the list of our data changes such as adding, delete or modify certain elements.

Getting event click on elements in the ListView

We often work with the elements in the list by clicking on the elements that. For example, click on one of the contacts to open to see details about that person,… So how to catch the click event of the ListView element? You just setOnItemClickListener for ListView is finished.

lvTut.setOnItemClickListener(new AdapterView.OnItemClickListener() {
    @Override
    public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
        Toast.makeText(context, listData.get(i), Toast.LENGTH_SHORT).show();
        // do something
    }
});

in function onItemClick do you see the variable int i, it is the position of the element is clicked in our list which.

This article here is finished. Next article will be more difficult so you need to hold this post firmly into offline.