Java 使用自定义适配器在一个listview中扩展两个布局时出现问题
我正在一个列表视图中扩展两个布局。数据是json格式的。我要做的是将json连接在一起,并检查每个布局的适当位置(第一个布局仅显示从位置0到第一个json的长度-1) 当列表视图变长时会出现问题,我可以向下滚动浏览它。它出现了一个空指针异常。所以我对一些代码进行了注释,错误消失了。但我得到的并不是我所期望的: 它随机交换格式。(假设第一个json的长度是x,所以0到x-1应该是第一个布局。但是当我上下滚动时,有时介于0和x之间的某个位置会更改为第二个布局。以及其他行>x,有时会更改为第一个布局) 下面是适配器的代码Java 使用自定义适配器在一个listview中扩展两个布局时出现问题,java,android,android-listview,adapter,Java,Android,Android Listview,Adapter,我正在一个列表视图中扩展两个布局。数据是json格式的。我要做的是将json连接在一起,并检查每个布局的适当位置(第一个布局仅显示从位置0到第一个json的长度-1) 当列表视图变长时会出现问题,我可以向下滚动浏览它。它出现了一个空指针异常。所以我对一些代码进行了注释,错误消失了。但我得到的并不是我所期望的: 它随机交换格式。(假设第一个json的长度是x,所以0到x-1应该是第一个布局。但是当我上下滚动时,有时介于0和x之间的某个位置会更改为第二个布局。以及其他行>x,有时会更改为第一个布局)
public class CustomAdapter extends BaseAdapter {
private Activity activity;
private JSONArray data;
private static LayoutInflater inflater=null;
private SecondItem second_item;
private FirstItem first_item;
private int firstLength;
private boolean hasFirst = false;
public CustomAdapter(Activity a, JSONArray firstArray, JSONArray secondArray) {
activity = a;
first_item = new FirstItem (firstArray);
second_item = new SecondItem (secondArray);
firstLength = first_item.getLength();
if (!firstArray.isNull(0)) {
data=CustomUtils.concatJsonArray(firstArray, secondArray);
hasFirst = true;
}
else
data = secondArray;
inflater = (LayoutInflater)activity.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
public int getCount() {
// TODO Auto-generated method stub
return data.length();
}
public Object getItem(int position) {
// TODO Auto-generated method stub
return position;
}
public long getItemId(int position) {
// TODO Auto-generated method stub
return position;
}
public static class ViewHolder{
public TextView txt_both;
public TextView txt_first_only;
...
}
public View getView(final int position, View convertView, ViewGroup parent) {
// TODO Auto-generated method stub
View vi=convertView;
ViewHolder holder;
if(convertView==null){
if (position < firstLength && hasFirst) {
vi = inflater.inflate(R.layout.first_item, null);
}
else {
vi = inflater.inflate(R.layout.second_item, null);
}
holder=new ViewHolder();
holder.txt_both=(TextView)vi.findViewById(R.id.txt_both);
...
if (position < firstLength && hasFirst) {
holder.txt_firstOnly=(TextView)vi.findViewById(R.id.txt_firstOnly);
...
}
vi.setTag(holder);
}
else
holder=(ViewHolder)vi.getTag();
if (position < firstLength && hasFirst) {
holder.txt_both.setText(first_item.getContent(position));
...
下面是代码的其余部分:
}
else {
holder.txt_both.setText(second_item.getContent(position - firstLength));
...
}
return vi;
}
}
您的自定义适配器应该覆盖方法
getViewTypeCount()
和getItemViewType(int位置)
。现在,操作系统认为所有视图都具有相同的视图类型,因此它可以任意传入以前创建的视图。正如您所见,有时这不是该职位的正确视图。thx的答案。。这真是鼓舞人心。。关于这些方法,我得到了很好的参考。
}
else {
holder.txt_both.setText(second_item.getContent(position - firstLength));
...
}
return vi;
}
}