为什么"解锁"滚动后项目是否已禁用?

时间:2013-07-15 01:24:51

标签: java android android-listview android-arrayadapter

我编写了一个自定义适配器(LevelAdapter因为我显示的游戏关卡列表),它从虚拟对象列表中填充ListView片段。每个虚拟对象都拥有一个布尔“未锁定”属性,我试图有条件地禁用并为列表中的每个项设置一些样式属性,具体取决于底层虚拟项是否“未锁定”。为此,我还使用了ViewHolder

以下代码正常工作,直到用户向下滚动并向上滚动,此时“未锁定”项目不会被禁用,但它们确实会失去适当的样式。

public class LevelAdapter extends ArrayAdapter<DummyContent.DummyItem> {
    private List<DummyContent.DummyItem> objects;
    private DummyContent.DummyItem item;
    private Context context;
    private int textViewResourceId;
    private int resource;

    public LevelAdapter(Context context, int resource, int textViewResourceId, List<DummyContent.DummyItem> objects) {
        super(context, resource, textViewResourceId, objects);
        this.objects = objects;
        this.context = context;
        this.resource = resource;
        this.textViewResourceId = textViewResourceId;

    }

    static class ViewHolder {
        TextView text;
        int position;
        boolean unlocked;
    }

    public View getView(int position, View convertView, ViewGroup parent) {
        View v = convertView;


        // https://developer.android.com/training/improving-layouts/smooth-scrolling.html#ViewHolder
        ViewHolder holder;
        if (v == null) {
            LayoutInflater vi = (LayoutInflater) context.getSystemService(context.LAYOUT_INFLATER_SERVICE);
            v = vi.inflate(resource, null);
            holder = new ViewHolder();
            holder.text = (TextView) v.findViewById(textViewResourceId);
            holder.position = position;
            v.setTag(holder);
        } else {
            holder = (ViewHolder) v.getTag();
        }

        item = objects.get(position);
        holder.text.setText(item.title);

        if (item.unlocked == false) {
            holder.text.setTextColor(Color.LTGRAY);
            Typeface type = Typeface.create("", Typeface.ITALIC);
            holder.text.setTypeface(type);
        }

        return v;
    }

    @Override
    public boolean areAllItemsEnabled() {
        return true; // technically untrue, but a hack to show the line divider between items
    }

    @Override
    public boolean isEnabled(int position) {

        item = objects.get(position);
        if (item.unlocked == true) {
            return true;
        } else {

            return false;
        }

    }

} 

1 个答案:

答案 0 :(得分:0)

    if (item.unlocked == false) {
        holder.text.setTextColor(Color.LTGRAY);
        Typeface type = Typeface.create("", Typeface.ITALIC);
        holder.text.setTypeface(type);
    }

您应该为unlocked == true案例创建else语句。

现在,如果适配器获得视图以重新使用具有未锁定错误的项目以填充已解锁的项目,则不会更改样式但保留旧样式。