一、效果图
二、XML代码
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<ListView
android:id="@+id/lv1"
android:layout_width="match_parent"
android:layout_height="wrap_content">
</ListView>
</LinearLayout>
三、Java代码
package com.example.administrator.app_adapter;
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;
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//初始化ListView
ListView lv1 = findViewById(R.id.lv1);
//创建数据源
final String data[] = {"数据1","数据2","数据3","数据4","数据5"};
//将数据装入适配器;参数1:上下文(当前Activity);参数2:样式;参数3:数据源;
ArrayAdapter arrayAdapter = new ArrayAdapter<>(this,
android.R.layout.simple_list_item_1,data);
//为ListView添加适配器
lv1.setAdapter(arrayAdapter);
//为每个按钮添加点击事件
lv1.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
//点击事件
Toast.makeText(MainActivity.this, data[position], Toast.LENGTH_SHORT).show();
}
});
}
}
标签:widget,lv1,ArrayAdapter,适配器,import,android,ListView,Adapter From: https://blog.51cto.com/u_13272819/6079178