ListViewDemo

《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>

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值