The use of ListView can be roughly divided into four steps: adding the ListView component, storing data, setting the layout file of the list item, loading data/resources for display, and adding monitoring.
This article mainly talks about the simplest usage of ArrayAdapter
The example effect is as follows:
main layout file
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".MainActivity">
<ListView
android:id="@+id/lvTest"
android:layout_width="match_parent"
android:layout_height="match_parent"/>
</LinearLayout>
The layout file of list_item (of course, it is also possible to use ArrayAdapter without defining this item layout. You can use the android.R.layout.simple_list_item_1 that comes with the system):
<?xml version="1.0" encoding="UTF-8"?>
<TextView xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:textColor="#FF00FF"
android:padding="15dp"
android:textSize="16sp"
>
</TextView>
MainActivity.java
package com.example.ArrayAdapter;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.Toast;
import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//1. 准备数据源
ListView listview = findViewById(R.id.lvTest);
final String[] citys = {"上海","北京","天津","江苏","河南","西藏","新疆","湖南","湖北"};
/* List<String> listdata = new ArrayList<String>();
listdata.add("上海");
listdata.add("北京");
listdata.add("天津");
listdata.add("江苏");
*/
//2.将数据源添加到适配器中 android.R.layout.simple_list_item_1 为内置默认Item布局,这里可以自定义比如:R.layout.list_item
ArrayAdapter arrayAdapter = new ArrayAdapter(MainActivity.this, R.layout.list_item, citys); //listdata和citys均可
//3. 将适配器中的数据添加到ListView 中
listview.setAdapter(arrayAdapter);
//为 ListView 的列表项添加鼠标点击事件
listview.setOnItemClickListener(new AdapterView.OnItemClickListener() {
/**
* @param adapterView 发生单击事件的列表项 ListView
* @param view 被单击控件 view
* @param i 在列表项中的位置 position
* @param l 被单击列表项的行ID
*/
@Override
public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
String Tag = "onItemClick======";
Log.d(Tag, "position=" + i);
Log.d(Tag, "行 ID" + l);
Toast.makeText(MainActivity.this, citys[i], Toast.LENGTH_SHORT).show();
}
});
}
}