本文为个人理解,如有错误请多指教。
**** 1. 使用ArrayAdapter适配器创建ListView
先写一个适配器布局
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android
android:layout_height="match_parent"
android:layout_width="match_parent"
android:orientation="horizontal"
>
<TextView
android:layout_height="match_parent"
android:layout_width="0dp"
android:layout_weight="1"
android:id="@+id/name"
/>
<TextView
android:layout_height="match_parent"
android:layout_width="0dp"
android:layout_weight="3"
android:id="@+id/age"
/>
</LinearLayout>
定义一个实体类,用于适配ListView
public class Item{
private String name;
private String age;
public Item(String name,String age){
this.name = name;
this.age = age;
}
public String getName(){
return name;
}
public String getAge(){
return age;
}
}
编写adapter适配器类,这个类继承ArrayAdapter
public class adapter extend ArrayAdapter(){
int id;
public adapter(Context context,int resource,List list){
super(context,resource,list);
id = resource;
}
public View getView(int position,View convertView,ViewGroup parent){
View view = LayoutInflater.from(parent.getContext()).inflate(id,parent,false);
Item item = (Item)getItem(position);
TextView textView1 = view.findViewById(R.id.name);
TextView textView2 = view.findViewById(R.id.age);
textView1.setText(item.getName());
textView2.setText(item.getAge());
return view;
}
}
然后在布局留下ListView的空间,并简单的写一个ListView布局,就像这样
<ListView
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="1"
android:id="@+id/list"
/>
在活动中获取ListView,并传入数值。
public class MainActivity extends AppCompatActivity {
List list = new ArrayList();
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.layout);
init();
ListView list1 = findViewById(R.id.list);
adapter a = new adapter(this,R.layout.item, list);
list1.setAdapter(a);
}
public void init(){
Item item = new Item("aa","aaaa");
list.add(item);
}
}
结果如下
![在这里插入图片描述](https://i-blog.csdnimg.cn/blog_migrate/9a41f3b40b39974bbec0d19697291cf5.png)