package com.lidaochen.test; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.ArrayAdapter; import android.widget.BaseAdapter; import android.widget.ListView; import android.widget.TextView; public class MainActivity extends AppCompatActivity { String objects[] = {"老张", "老王", "老李", "老刘", "老花生米", "老板"}; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); // 找到ListView控件 ListView listView = (ListView)findViewById(R.id.lv); // 创建一个ArrayAdapter // ArrayAdapter<String> adapter = new ArrayAdapter<>(this, R.layout.item, objects); ArrayAdapter<String> adapter = new ArrayAdapter<>(this, R.layout.item1, R.id.tv_name, objects); // 设置数据适配器 listView.setAdapter(adapter); } }
<?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"> <TextView android:layout_width="match_parent" android:layout_height="wrap_content" android:id="@+id/tv_name" android:textSize="20sp"/> </LinearLayout>
item.xml
<?xml version="1.0" encoding="utf-8"?> <TextView xmlns:android="http://schemas.android.com/apk/res/android" android:id="@+id/textView1" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="TextView" android:textAppearance="?android:attr/textAppearanceLarge" />