当我使用自定义适配器向上和向下滚动listview时,getView()开始表现得很奇怪.为什么?

oli*_*ite 5 android listview scroll adapter

我有一个listview与自定义arrayadapter处理大约15个字符串.每行的样式交替显示(标签和这些标签的值之间 - 例如,第1行可以是"电子邮件地址",第2行是实际的电子邮件地址).我在arrayadapter的getView()方法中将每行的样式更改为替换.因此,如果当前位置的项目是标签,我将从默认的行样式(这是值应用于它们的样式)更改样式.当列表视图首次加载时,样式是完美的,正如我想要的那样.如果我慢慢向上或向下滚动列表,它会保持这种状态.但是,如果我快速上下滚动列表,值行的样式将开始更改为标签行的样式,直到所有行都具有标签行的样式.有谁知道为什么会发生这种情况?我在应用程序的其他列表视图中使用了自定义适配器,没有这样的问题.

编辑:发现它还将所有行更改为纵向 - >横向方向更改上的标签样式.不在横向 - >纵向更改上执行此操作.下面是我正在使用的适配器.我错过了什么吗?

public class DetailsAdapter extends ArrayAdapter<String> {

private TextView text = null;
private String item = null;

public DetailsAdapter(Context context, int resource, int textViewResourceId, String[] objects) {
    super(context, resource, textViewResourceId, objects);
}

@Override
public View getView(int position, View convertView, ViewGroup parent) {
    text = (TextView) super.getView(position, convertView, parent);
    item = getItem(position);
    if (item.equals("Name") || item.equals("Mobile") || item.equals("Home") || item.equals("Email") || item.equals("Address")) {
        text.setBackgroundColor(0xFF575757);
        text.setTextSize(15);
        text.setTypeface(null, Typeface.BOLD);
        text.setPadding(8, 5, 0, 5);
    } else {
        text.setPadding(15, 15, 0, 15);
    }
    return text;
}

@Override
public boolean isEnabled(int position) {
    item = getItem(position);
    if (item.equals("Name") || item.equals("Mobile") || item.equals("Home") || item.equals("Email") || item.equals("Address")) {
        return false;
    } else {
        return true;
    }
}
}
Run Code Online (Sandbox Code Playgroud)

小智 7

Android非常积极地重用视图,并且很可能将用作电子邮件地址行的视图重新用于应该显示标签的行,反之亦然.

因此,您不能依赖"默认"值.在所有情况下设置填充,字体,文本大小和背景颜色:

if (item.equals("Name") || item.equals("Mobile") || item.equals("Home") || item.equals("Email") || item.equals("Address")) {
    text.setBackgroundColor(0xFF575757);
    text.setTextSize(15);
    text.setTypeface(null, Typeface.BOLD);
    text.setPadding(8, 5, 0, 5);
} else {
    text.setBackgroundColor(DEFAULT_BACKGROUND);
    text.setTextSize(DEFAULT_TEXT_SIZE);
    text.setTypeface(null, DEFAULT_TYPEFACE);
    text.setPadding(15, 15, 0, 15);
}
Run Code Online (Sandbox Code Playgroud)