《Android应用程序开发(第三版)》王向辉 张国印 沈洁 编著 清华大学出版社
MainActivity.java
package com.example.listviewdemo;
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.TextView;
import java.util.ArrayList;
import java.util.List;
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final TextView textView=(TextView)findViewById(R.id.textView);
ListView listView=(ListView)findViewById(R.id.listView);
List<String> list=new ArrayList<String>();
list.add("ListView子项1");
list.add("ListView子项2");
list.add("ListView子项3");
ArrayAdapter<String> adapter=new ArrayAdapter<String>(this,android.R.layout.simple_list_item_1,list);
listView.setAdapter(adapter);
AdapterView.OnItemClickListener listViewListener=new AdapterView.OnItemClickListener(){
@Override
public void onItemClick(AdapterView<?>arg0,View arg1,int arg2,long arg3){
String msg="父View:"+arg0.toString()+"\n"+"子View:"+arg1.toString()+"\n"+"位置:"+String.valueOf(arg2)+",ID:"+String.valueOf(arg3);
textView.setText(msg);
}
};
listView.setOnItemClickListener(listViewListener);
}
}
activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent"
android:layout_height="match_parent" tools:context="com.example.listviewdemo.MainActivity">
<TextView
android:id="@+id/textView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Hello World!"
tools:layout_editor_absoluteY="0dp"
tools:layout_editor_absoluteX="5dp" />
<ListView
android:id="@+id/listView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
tools:layout_editor_absoluteX="0dp"
android:layout_marginTop="18dp"
app:layout_constraintTop_toBottomOf="@+id/textView">
</ListView>
</android.support.constraint.ConstraintLayout>