欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

Android07-高级控件-ListView

程序员文章站 2022-07-14 18:04:41
...
ListView:先在XML写一个高级控件ListView
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical" android:layout_width="match_parent"
    android:layout_height="match_parent">

    <ListView
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:id="@+id/lv_list_names"
        ></ListView>


</LinearLayout>

然后去Activity写如下代码:
package com.zking.g160628_android07_widgetplus;

import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.app.AppCompatActivity;
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;

/**
 * @author Zking-Snail
 * @time 2017/6/8 11:18
 * @Version ${REV}
 */
public class ListActivity extends AppCompatActivity {

    private ListView lv_list_names;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_list);
        lv_list_names = (ListView) findViewById(R.id.lv_list_names);

        final List<String> names=new ArrayList<>();
        for (int i = 0; i <100; i++) {
            names.add("张"+i);
        }

        ArrayAdapter adapter=new ArrayAdapter(this,android.R.layout.simple_list_item_1,names);

        lv_list_names.setAdapter(adapter);

        //给ListView设置点击事件
        lv_list_names.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
                Toast.makeText(ListActivity.this, names.get(i), Toast.LENGTH_SHORT).show();
            }
        });
    }
}