我有3个标签,其中一个标签上有联系方式的列表视图,无法使其正常工作。
listview位于片段布局中,ID为 list 。我在尝试访问该标签时遇到此错误:
java.lang.ArrayIndexOutOfBoundsException: length=2; index=2 at com.gabrielfiocchi.packemovilvq.ListaParaTabContacto.getView(ListaParaTabContacto.java:42)
This有效,但不适用于此自定义适配器。
以下代码:
TabContacto.java
import android.support.v4.app.Fragment;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ListView;
public class TabContacto extends Fragment{
String[] web = {
"Correo",
"Twitter",
"Teléfono"
} ;
String[] datos = {
"info@somemail.com",
"@sometwitter",
"+0123456789"
} ;
Integer[] imageId = {
R.drawable.img_mail,
R.drawable.img_twitter,
};
ListView lv;
@Override
public View onCreateView(LayoutInflater inflater,
ViewGroup container, Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.fragment_contacto, container, false);
perform(v);
return v;
}
public void perform(View v) {
lv = (ListView) v.findViewById(R.id.list);
ListaParaTabContacto adapter = new ListaParaTabContacto(getActivity(), web, datos, imageId);
lv.setAdapter(adapter);
}
}
这是我的自定义适配器: ListaParaTabContacto
import android.app.Activity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.TextView;
public class ListaParaTabContacto extends ArrayAdapter<String> {
private final Activity context;
private final String[] web;
private final String[] datos;
private final Integer[] imageId;
public ListaParaTabContacto(Activity context,
String[] web, String[] datos, Integer[] imageId) {
super(context, R.layout.list_single, web);
this.context = context;
this.web = web;
this.datos = datos;
this.imageId = imageId;
}
@Override
public View getView(int position, View view, ViewGroup parent) {
LayoutInflater inflater = context.getLayoutInflater();
View rowView = inflater.inflate(R.layout.list_single, null, true);
TextView txtTitle = (TextView) rowView.findViewById(R.id.txt);
TextView txtTitle2 = (TextView) rowView.findViewById(R.id.txt2);
ImageView imageView = (ImageView) rowView.findViewById(R.id.img);
txtTitle.setText(web[position]);
txtTitle2.setText(datos[position]);
imageView.setImageResource(imageId[position]);
return rowView;
}
}
提前致谢!
答案 0 :(得分:0)
问题是imageId
数组只有2个值。
ArrayAdapter
构造函数的第三个参数是要在ListView
中显示的元素。因此,基于web
数组,Adapter
中有3个元素。
当ListView
构造的最后一个元素position = 2
时,您访问位置无效的imageId
数组,抛出ArrayIndexOutOfBoundsException
。
您必须向imageId
添加一个项目或移除web
数组的任何元素(ListView
将包含2个元素)或在访问其位置之前检查position < imageId.length
是否