一、ArrayAdapter 只显示文字
activitylistview_layout.xml
<?xml version="1.0" encoding="utf-8"?> <ListView xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="match_parent" android:id="@+id/listview_1" android:divider="#0f0" android:dividerHeight="2dp"> </ListView>
listview_layout.xml
<?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="50dp" android:textSize="30dp" android:gravity="center_vertical" android:paddingLeft="10dp"> </TextView>
java
Activitylistview.java
package com.example.chenshuai.test321; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.view.View; import android.widget.AdapterView; import android.widget.ArrayAdapter; import android.widget.ListView; import android.widget.Toast; import java.util.ArrayList; import java.util.List; public class Activitylistview extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activitylistview_layout); ListView listview_1 = (ListView)findViewById(R.id.listview_1); //设置listview的适配器Adapter //准备数据 //String[] str_1 = {"a","b","c","d","e","f","g","h","i","j","k","l"}; //另一种写法 List<String> list = new ArrayList<String>(); list.add("a"); list.add("b"); list.add("c"); list.add("d"); list.add("e"); list.add("f"); list.add("g"); list.add("h"); list.add("i"); list.add("j"); list.add("k"); list.add("l"); list.add("m"); list.add("n"); //构造适配器 ArrayAdapter adapter = new ArrayAdapter(this,R.layout.listview_layout,list); //设置适配器 listview_1.setAdapter(adapter); //监听事件 listview_1.setOnItemClickListener(new AdapterView.OnItemClickListener() { @Override public void onItemClick(AdapterView<?> parent, View view, int position, long id) { //通过下标来获取内容 String str = parent.getItemAtPosition(position).toString(); Toast.makeText(Activitylistview.this, str, Toast.LENGTH_SHORT).show(); //position 数据的下标 id 数据的id Toast.makeText(Activitylistview.this, "position="+position+"id="+id, Toast.LENGTH_SHORT).show(); } }); } }
时间: 2024-10-06 19:43:23