Android 数组适配器(ArrayAdapter)
1,编写xml代码
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
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"
android:orientation="vertical"
tools:context=".MainActivity">
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="智慧校园"
android:textSize="50dp"
></TextView>
<ListView
android:id="@+id/list"
android:layout_width="match_parent"
android:layout_height="wrap_content"
/>
</LinearLayout>
2,编写类
package com.example.listviewtest;
import androidx.appcompat.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 android.widget.Toast;
public class MainActivity extends AppCompatActivity {
// 这三个东西 显示 数据
private ListView list;
private String[] data ={"企业会话","办公邮件","账务信息查询"};
private ArrayAdapter<String> adapter;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// 找id
list = (ListView)findViewById(R.id.list);
// 实例化
adapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1,data);
// 添加数据 ;
list.setAdapter(adapter);
// 渲染数据 ;
list.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Toast.makeText(getApplicationContext(),data[position],Toast.LENGTH_SHORT).show();
// data[position] ==>((TextView)view).getText()
// adapter.getItem(position);
}
});
}
}
3,运行结果截图