[JAVA] I saw the list view of Android development collectively

Introduction

Hello. I'm Wataku, a server-side programmer who is studying programming at a certain school. : relaxed: Let's develop Android this time as well. Since there are various ways to display list views on Android, I myself have become confused, so I would like to sleep with the devil.

Target person

--A person who can write Java somehow. --Someone who is ambiguous in Android development but can do it a little.

List view basics

List tap listener

○ Listener class when tapping the list view: ** onItemClickListener ** Implement the interface. * This interface is a member interface of the AdapterView class ○ List setting method

setOnItemClickListener(Insert the member interface that implements onItemClickListener)

Get tap element

** 1) Event handler: onItemClick () ** 4 arguments

1.AdapterView<?> parent 
->The entire tapped ListView

2.View view
->One line of tapped screen parts

3.int position
->Tapped line number
* Starting from 0

4.long id
->Primary key value when ListView is generated based on DB data
* If DB is not used, the same value as the above position

** 2) Data acquisition ** ○ The data of the tapped line can be obtained using parent and position.

(String)parent.getItemAtPosition(position)

Sample code


private class ListItemClickListener implements AdapterView.OnItemClickListener {
    public void onItemClick(AdapterView<?> parent, View view, int position, long l) {
        String item = (String)parent.getItemAtPosition(position);
        Toast.makeText(ListClickSampleActivity.this, show, Toast.LENGTH_SHORT).show();
    }
}

Static list view

** 1) Create with xml **

activity_list_click_sample.xml


<?xml version="1.0" encoding="utf-8"?>
<ListView
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/lvMenu"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:entries="@array/lv_menu"/>

string.xml


<?xml version="1.0" encoding="UTF-8" ?>
<resources>
    <string name="app_name">List selection sample</string>
    <string-array name="lv_menu">
        <item>Fried chicken</item>
        <item>Hamburger set meal</item>
        <item>Ginger-grilled set meal</item>
        <item>Steak set meal</item>
        <item>Stir-fried vegetables set meal</item>
        <item>Twice-cooked meat set meal</item>
        <item>Mapo tofu set meal</item>
        <item>Tonkatsu set meal</item>
        <item>Minced cutlet set meal</item>
        <item>Chicken and set meal</item>
        <item>Croquette set meal</item>
        <item>Grilled fish set meal</item>
        <item>Yakiniku set meal</item>
        <item>Weak meat and strong food</item>
    </string-array>
</resources>

ListClickSampleActivity.java


public class ListClickSampleActivity extends AppCompatActivity {

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

        ListView lvMenu = findViewById(R.id.lvMenu);
        lvMenu.setOnItemClickListener(ListItemClickListener);

    }

    AdapterView.OnItemClickListener ListItemClickListener = new AdapterView.OnItemClickListener() {
        @Override
        public void onItemClick(AdapterView<?> parent, View view, int position, long l) {
            String item = (String)parent.getItemAtPosition(position);
            String show = "Set meal of your choice:" + item;
            Toast.makeText(ListClickSampleActivity.this, show, Toast.LENGTH_SHORT).show();
        }
    };
}

** 2) Create with Java code **

<?xml version="1.0" encoding="utf-8"?>
<ListView
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/lvPref"
    android:layout_width="match_parent"
    android:layout_height="match_parent">
</ListView>

PrefListActivity.java


public class PrefListActivity extends AppCompatActivity {
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_pref_list);

        ListView lvPref = findViewById(R.id.lvPref);

        List<String> prefList = createPrefectureList();
        ArrayAdapter<String> adapter = new ArrayAdapter<>(PrefListActivity.this, android.R.layout.simple_list_item_1, prefList);
        lvPref.setAdapter(adapter);

        lvPref.setOnItemClickListener(new ListItemClickListener());
    }

    /**
     *A method to generate a state list.
     * @return State list object.
     */
    private List<String> createPrefectureList() {
        List<String> prefList = new ArrayList<>();
        prefList.add("Hokkaido");
        prefList.add("Aomori Prefecture");
        prefList.add("Iwate Prefecture");
        prefList.add("Miyagi Prefecture");
        prefList.add("Akita");
        prefList.add("Yamagata Prefecture");
        prefList.add("Fukushima Prefecture");
        prefList.add("Ibaraki Prefecture");
        prefList.add("Tochigi Prefecture");
        prefList.add("Gunma Prefecture");
        prefList.add("Saitama");
        prefList.add("Chiba");
        prefList.add("Tokyo");
        prefList.add("Kanagawa Prefecture");
        prefList.add("Niigata Prefecture");
        prefList.add("Toyama Prefecture");
        prefList.add("Ishikawa Prefecture");
        prefList.add("Fukui prefecture");
        prefList.add("Yamanashi Prefecture");
        prefList.add("Nagano Prefecture");
        prefList.add("Gifu Prefecture");
        prefList.add("Shizuoka Prefecture");
        prefList.add("Aichi prefecture");
        prefList.add("Mie Prefecture");
        prefList.add("Shiga Prefecture");
        prefList.add("Kyoto");
        prefList.add("Osaka");
        prefList.add("Hyogo prefecture");
        prefList.add("Nara Prefecture");
        prefList.add("Wakayama Prefecture");
        prefList.add("Tottori prefecture");
        prefList.add("Shimane Prefecture");
        prefList.add("Okayama Prefecture");
        prefList.add("Hiroshima Prefecture");
        prefList.add("Yamaguchi Prefecture");
        prefList.add("Tokushima Prefecture");
        prefList.add("Kagawa Prefecture");
        prefList.add("Ehime Prefecture");
        prefList.add("Kochi Prefecture");
        prefList.add("Fukuoka Prefecture");
        prefList.add("Saga Prefecture");
        prefList.add("Nagasaki Prefecture");
        prefList.add("Kumamoto Prefecture");
        prefList.add("Oita Prefecture");
        prefList.add("Miyazaki prefecture");
        prefList.add("Kagoshima prefecture");
        prefList.add("Okinawa Prefecture");
        return prefList;
    }

    /**
     *A member class that describes what happens when a list is selected.
     *Transfer the process to the second screen.
     */
    private class ListItemClickListener implements AdapterView.OnItemClickListener {
        @Override
        public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
            String prefName = (String) parent.getItemAtPosition(position);

            Intent intent = new Intent(PrefListActivity.this, PrefEditActivity.class);
            intent.putExtra("selectedPrefNo", position);
            intent.putExtra("selectedPrefName", prefName);
            startActivity(intent);
        }
    }
}

Dynamic list view

Use the ** SimpleCursorAdapter ** class. → Use when you want to create a list view based on the data in the DB. 6 arguments

1.context

2.R-value that represents the layout of each row in the list view
*simple_list_view_item_1 is usually good.

3.Cursor object

4.String[] :Array of column names

5.int[] :Array of R-values of screen parts

6.0 is fine

How to display (register) this in the list view -> Use the ** setAdapter ** method of the ListView class

Sample code

MemoListActivity.java


public class MemoListActivity extends AppCompatActivity {
    private ListView _lvMemoList;

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

        _lvMemoList = findViewById(R.id.lvMemoList);
        _lvMemoList.setOnItemClickListener(new ListItemClickListener());
    }

    @Override
    protected void onResume() {
        super.onResume();
        DatabaseHelper helper = new DatabaseHelper(MemoListActivity.this);
        SQLiteDatabase db = helper.getWritableDatabase();
        Cursor cursor = DataAccess.findAll(db);
        String[] from = {"title"};
        int[] to = {android.R.id.text1};
        SimpleCursorAdapter adapter = new SimpleCursorAdapter(MemoListActivity.this, android.R.layout.simple_list_item_1, cursor, from, to, 0);
        _lvMemoList.setAdapter(adapter);
    }
}

ʻonResume: Method to refresh the screen `

Customize list

Use ** SimpleAdapter **. row To customize each row in the list view, do the following: ** 1) Prepare a layout .xml file for one line ** -> How to write xml file is the same as normal layout file

res/layout/row.xml


<LinearLayout ... >
    <ImageView ... />
    <TextView ... /> 
    <TextView ... /> 
    <TextView ... />
</LinearLayout>

* File name can be anything

** 2) Specify the R value of the file in 1) in the argument that specifies the layout when newing the adapter. ** **

(ex.)
new.SimpleAdapter( ..., _list, R.layout.row, ... );

** 3) In the int array of the argument to when newing the adapter class, specify the R value of id described in the file of 1). ** **

(ex.)
int[] to = {R.id.tvMenuName, R.id.tvMenuPrice}

ViewBinder ** (1) What is ViewBinder ** You can use row.xml to customize the layout that precedes the list view.

Then, how to change the display contents of each line according to the data?

Create your own process to assign from data to to screen parts by combining from-to (creating ViewBinder), the procedure is as follows.

** 1) Create a class that implements the SimpleAdapter.ViewBinder interface. -> Private member class is fine **

** 2) Describe the data allocation process to the screen parts in the setViewValue () method of this class. (See below) **

** 3) Pass a new version of this class to the setViewBinder () method of the adapter class **

(ex.) 
private class CustomViewBinder implement SimpleAdapter.ViewBinder {
    @Override
    public boolean setViewValue() { 

Describe the data allocation of screen parts in each line here
    }  
}

adapter.setViewBinder(new CustomViewBinder());

** (2) Argument of setViewValue () ** The argument of the method of setViewValue () is the following three.

1. View view :Screen parts in one line.
2. Object data :The data to assign to the first argument above.
3. String textReprosentation :A string of the contents of the second argument. If the second argument is null
White space string.

** (3) Processing pattern in setViewValue () ** In setViewValue (), branch using the id of the argument view, and describe the process using the argument data. → The switch statement is convenient.

public booelan setViewValue ( .... ) {
  int viewId = view.getId();← Get id
  switch( viewId ) {← Branch processing according to id(switch)
    case R . id . imPhoneType :← R value because it is a comparison between ids
      ImageView imPhoneType = ( ImageView ) view;
      int phoneType = ( Integer ) data;

Then do whatever you want.

      return true;     
    case .....
  }
  return false
}

In the setViewValue () method, if you write your own process to embed data in the view, that is, write return true at the end of each case. In addition, write return false at the end of the method. → Based on this return value, it is judged whether to embed data on the os side.

** (4) For SimpleCursorAdapter ** Even in the case of SimpleCursorAdapter, the processing of setViewValue () of ViewBinder is the same as that of SimpleAdapter.

view . getId()Branch the value of with a switch. However, the arguments are the following three.
1. View view :Screen parts in one line of the list.
2. Cursor cursor :A cursor object that contains data for one row of the target list.
3. int columnIndex :The column index of the data to be assigned to the first argument above.

Reloading DB data

When the data in the DB that is the original data of the list view is updated, it is necessary to retrieve the data from the DB and display it again.

○ The following source code.
SimpleCursorAdapter adapter = ( SimpleCursorAdapter ) _lvPhones . getAdapter();

adapter . changeCursor( cursor );← Swap the cursor. New cursor

(note) If you want to set the adapter with `ʻonCreate () and set (replace) the cursor with onResume (), you can pass null as the argument cursor when you new SimpleCursorAdapter in onCreate (). ``

Sample code 1

public class CustomizedListView2Activity extends AppCompatActivity {
    /**
     *List data to be displayed in the list view.
     */
    private List<Map<String, Object>> _list;

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

        _list = createList();

        String[] from = {"phoneType", "phoneNo", "phoneSex"};
        int[] to = {R.id.imPhoneType, R.id.tvPhoneNo, R.id.tvSex};
        SimpleAdapter adapter = new SimpleAdapter(CustomizedListView2Activity.this, _list, R.layout.row, from, to);
        adapter.setViewBinder(new CustomViewBinder());
        ListView lvPhones = findViewById(R.id.lvPhones);
        lvPhones.setAdapter(adapter);
    }

    /**
     *A method that generates the list data displayed in the list view.
     *
     * @return The generated list data.
     */
    private List<Map<String, Object>> createList() {
        List<Map<String, Object>> list = new ArrayList<>();

        for (int i = 1; i <= 30; i++) {
            int phoneType = (int) (3 * Math.random()) + 1;
            int phoneNoInt = (int) (99999999 * Math.random());
            int phoneSexInt = (int) (10*Math.random() + 1);

            String phoneNo = "090" + String.format("%08d", phoneNoInt);

            int phoneSex = 1;
            if(phoneSexInt <= 5) {
                phoneSex = 0;
            }

            Map<String, Object> map = new HashMap<>();
            map.put("phoneType", phoneType);
            map.put("phoneNo", phoneNo);
            map.put("phoneSex", phoneSex);
            list.add(map);
        }

        return list;
    }

    /**
     *List view custom view binder class.
     */
    private class CustomViewBinder implements SimpleAdapter.ViewBinder {

        @Override
        public boolean setViewValue(View view, Object data, String textRepresentation) {
            int viewId = view.getId();
            switch(viewId) {
                case R.id.imPhoneType:
                    ImageView imPhoneType = (ImageView) view;
                    int phoneType = (Integer) data;
                    switch(phoneType) {
                        case 2:
                            imPhoneType.setImageResource(android.R.drawable.ic_menu_crop);
                            break;
                        case 3:
                            imPhoneType.setImageResource(android.R.drawable.ic_menu_myplaces);
                            break;
                        default:
                            imPhoneType.setImageResource(android.R.drawable.ic_menu_call);
                            break;
                    }
                    return true;
                case R.id.tvPhoneNo:
                    TextView tvPhoneNo = (TextView) view;
                    String phoneNo = (String) data;
                    tvPhoneNo.setText(phoneNo);
                    return true;
                case R.id.tvSex:
                    TextView tvSex = (TextView) view;
                    int phoneSex = (Integer) data;
                    String sex = "♂";
                    if(phoneSex == 0) {
                        sex = "♀";
                    }
                    tvSex.setText(sex);
                    return true;
            }
            return false;
        }
    }
}

Sample code 2

public class CustomizedListView3Activity extends AppCompatActivity {
    
    private ListView _lvPhones;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_customized_list_view3);
        _lvPhones = findViewById(R.id.lvPhones);

        String[] from = {"phone_type", "phone_no", "phone_sex"};
        int[] to = {R.id.imPhoneType, R.id.tvPhoneNo, R.id.tvSex};
        SimpleCursorAdapter adapter = new SimpleCursorAdapter(CustomizedListView3Activity.this, R.layout.row, null, from, to, 0);
        adapter.setViewBinder(new CustomViewBinder());
        _lvPhones.setAdapter(adapter);
    }

    @Override
    public void onResume() {
        super.onResume();
        setNewCursor();
    }

    /**
     *A method that updates the cursor in the cursor adapter.
     */
    private void setNewCursor() {
        DatabaseHelper helper = new DatabaseHelper(CustomizedListView3Activity.this);
        SQLiteDatabase db = helper.getWritableDatabase();
        Cursor cursor = DataAccess.findAll(db);
        SimpleCursorAdapter adapter = (SimpleCursorAdapter) _lvPhones.getAdapter();
        adapter.changeCursor(cursor);
    }

    /**
     *List view custom view binder class.
     *
     * @author Shinzo SAITO
     */
    private class CustomViewBinder implements SimpleCursorAdapter.ViewBinder {

        @Override
        public boolean setViewValue(View view, Cursor cursor, int columnIndex) {
            int viewId = view.getId();
            switch(viewId) {
                case R.id.imPhoneType:
                    ImageView imPhoneType = (ImageView) view;
                    int phoneType = cursor.getInt(columnIndex);
                    switch(phoneType) {
                        case 2:
                            imPhoneType.setImageResource(android.R.drawable.ic_menu_crop);
                            break;
                        case 3:
                            imPhoneType.setImageResource(android.R.drawable.ic_menu_myplaces);
                            break;
                        default:
                            imPhoneType.setImageResource(android.R.drawable.ic_menu_call);
                            break;
                    }
                    return true;
                case R.id.tvPhoneNo:
                    TextView tvPhoneNo = (TextView) view;
                    String phoneNo = cursor.getString(columnIndex);
                    tvPhoneNo.setText(phoneNo);
                    return true;
                case R.id.tvSex:
                    TextView tvSex = (TextView) view;
                    int phoneSex = cursor.getInt(columnIndex);
                    String sex = "♂";
                    if(phoneSex == 0) {
                        sex = "♀";
                    }
                    tvSex.setText(sex);
                    return true;
            }
            return false;
        }
    }
}

that's all. I've summarized the list view on Android. If you have any suggestions such as something wrong, please contact us. Thank you for reading to the end.

Recommended Posts

I saw the list view of Android development collectively
About the basics of Android development
<Android> Change the background color of the List row of ListView
Customize list view on Android
I will explain the difference between Android application development and iOS application development from the perspective of iOS engineers
[Java] Delete the elements of List
A newcomer tries to summarize the Android view (beginner Android application development)
I read the source of ArrayList I read
I opened the menu bar (option menu) on Android and saw it.
I read the source of Integer
I read the source of Long
Official logo list of the service
I thought about the strategy of introducing Combine in iOS development
I tried to take a look at the flow of Android development environment construction with Android Studio
I read the source of Short
I read the source of Byte
I read the source of String
I tried to summarize the key points of gRPC design and development
I stumbled upon the development and publication of my first iPhone app
Android development, how to check null in the value of JSON object
Understand the basics of Android Audio Record
I investigated the internal processing of Retrofit
[day: 5] I summarized the basics of Java
How to sort the List of SelectItem
Fix the view screen of the post page
Android view
Summarize the life cycle of Java objects to be aware of in Android development
The list of installed apps is not displayed in getPackageManager (Android11 ​​/ API level 30)
[No.004] Corrected the order list screen of the orderer
JAVA: jar, aar, view the contents of the file
I want to output the day of the week
[Android] [Java] Manage the state of CheckBox of ListView
I checked the place of concern of java.net.URL # getPath
Add empty data to the top of the list
Ominous odor list suggesting the possibility of refactoring
[Android] List all setting items on the setting screen
List of libraries useful for ios application development
I understood the very basics of character input
Browse an instance of Tab's View on Android
Improve the performance of your Docker development environment
I compared the characteristics of Java and .NET
The story of tuning android apps with libGDX
I want to var_dump the contents of the intent
Android Studio development for the first time (for beginners)
I touched on the new features of Java 15
I tried using the profiler of IntelliJ IDEA
I checked the number of taxis with Ruby
Try the free version of Progate [Java I]
Rails The concept of view componentization of Rails that I want to convey to those who want to quit
[Beginner's point of view] I tried to solve the FizzBuzz problem "easily" with Ruby!
A memorandum because I was addicted to the setting of the Android project of IntelliJ IDEA
Simple statistical analysis of monetary value from the list searched by Mercari Java development