ArrayAdapter三个参数和四个参数的使用区别:
//3参形式:public ArrayAdapter (Context context, int resource, T[] objects)//4参形式:public ArrayAdapter (Context context, int resource, int textViewResourceId, T[] objects)
参数介绍
- Context context //指上下文,一般写this,或者MainActivity.this
- int resource //指要加载的布局资源文件
- int textViewResourceId //指加载的布局文件中TextView的Id
- T[] objects //指要显示的数组
分析
3参和4参中的区别就是是否指定 int textViewResourceId //指加载的布局文件中TextView的Id
如果是4参,直接加入指定数据类型,执行顺利功过.
- 布局文件主页面
<?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"><ListViewandroid:id="@+id/lv"android:layout_width="match_parent"android:layout_height="match_parent"android:fastScrollEnabled="true"/></LinearLayout>
- 要加载的项目布局文件
<?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"><TextViewandroid:layout_width="wrap_content"android:layout_height="wrap_content"android:textSize="20sp"/></LinearLayout>
- MainActivity代码
public class MainActivity extends AppCompatActivity {@Overrideprotected void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);setContentView(layout.activity_main);ListView lv = findViewById(R.id.lv);//创建一个想要显示数据的数组String[] strings={"小红","小兰","小明","小芳"};//4参形式的用法ArrayAdapter<String>lists=new ArrayAdapter<String>(this, layout.item,R.id.tv,strings);lv.setAdapter(lists);}
}
- 运行结果
- 3参形式呢?
如果直接拿掉int textViewResourceId 参数运行是失败的
ArrayAdapter<String>lists=new ArrayAdapter<String>(this, layout.item,strings);
结果:
并且后台会报错: java.lang.IllegalStateException: ArrayAdapter requires the resource ID to be a TextView
所以3参形式并不是直接去掉资源Id,就能用,否则也不会有4参形式.
- 3参正确的用法
首先,重新建一个布局文件,但是这个布局文件与4参的不同,因为它没有相关的布局,仅有一个TextView.如下:
<?xml version="1.0" encoding="utf-8"?><TextView xmlns:android="http://schemas.android.com/apk/res/android"android:layout_width="wrap_content"android:layout_height="wrap_content"android:textSize="20sp"/>
然后,直接引用就可以了
ArrayAdapter<String>list=new ArrayAdapter<String>(this, R.layout.item2,strings);
这样两个方法都掌握好了,想用哪个就用那个.