(一)
1.效果图:
2.MainActivity.java
1 package com.example.app5; 2 3 import android.support.v7.app.AppCompatActivity; 4 import android.os.Bundle; 5 import android.widget.ArrayAdapter; 6 import android.widget.ListView; 7 8 import java.util.ArrayList; 9 import java.util.List; 10 11 public class MainActivity extends AppCompatActivity { 12 private ListView listView; 13 private List<String> list; 14 private ArrayAdapter arrayAdapter; 15 16 @Override 17 protected void onCreate(Bundle savedInstanceState) { 18 super.onCreate(savedInstanceState); 19 setContentView(R.layout.activity_main); 20 21 listView = (ListView) findViewById(R.id.lv); 22 23 24 //新建数据源 25 list = new ArrayList<>(); 26 for (int i=0;i<20;i++){ 27 list.add("listview子项"+i); 28 } 29 30 //新建适配器,适配器绑定数据 31 arrayAdapter = new ArrayAdapter(MainActivity.this,android.R.layout.simple_list_item_1,list); 32 /* arrayAdapter=new ArrayAdapter(MainActivity.this,R.layout.item,list);*/ 添加自定义的布局 33 34 //视图加载适配器 35 listView.setAdapter(arrayAdapter); 36 } 37 }
3.activity_mian.xml
1 <?xml version="1.0" encoding="utf-8"?> 2 <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" 3 xmlns:tools="http://schemas.android.com/tools" 4 android:layout_width="match_parent" 5 android:layout_height="match_parent" 6 android:paddingBottom="@dimen/activity_vertical_margin" 7 android:paddingLeft="@dimen/activity_horizontal_margin" 8 android:paddingRight="@dimen/activity_horizontal_margin" 9 android:paddingTop="@dimen/activity_vertical_margin" 10 tools:context="com.example.app5.MainActivity" 11 android:orientation="vertical"> 12 13 <ListView 14 android:id="@+id/lv" 15 android:layout_width="wrap_content" 16 android:layout_height="wrap_content" /> 17 </LinearLayout>
4.自定义的布局item.xml
1 <?xml version="1.0" encoding="utf-8"?> 2 <TextView 3 android:id="@+id/tv" 4 android:textColor="@color/colorAccent" 5 android:layout_width="match_parent" 6 android:layout_height="wrap_content" 7 xmlns:android="http://schemas.android.com/apk/res/android" />