'if'条件在BaseAdapter中无法正常工作

时间:2019-01-18 11:17:10

标签: android list if-statement baseadapter listadapter

我的BaseAdapter类的getView中有以下代码:

@Override
public View getView(final int position, View convertView, ViewGroup parent) {
    View v;
    if (convertView == null) {
        LayoutInflater inflater = (LayoutInflater) mContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        v = inflater.inflate(R.layout.listview_item, parent, false);
    } else {
        v = convertView;
    }
    LinearLayout mLayout = v.findViewById(R.id.layout_list_item);

    if (!mList.get(position).isOperative()) {
        mLayout.setBackgroundResource(R.drawable.list_item_background_inactive);
    } else {
        mLayout.setBackgroundResource(R.drawable.list_item_background_active);
    }

    TextView mTextOne = v.findViewById(R.id.text_one);
    TextView mTextTwo = v.findViewById(R.id.text_two);

    mTextOne.setText(mList.get(position).getPropertyOne());
    mTextTwo.setText(mList.get(position).getPropertyTwo());

    return v;
}

  

如果(!mList.get(position).isOperative())

我想进行背景设置,并且背景一开始就正确应用,但是如果滚动,则将丢失初始设置。

mList 中,存在具有3个属性的对象(字符串propertyOne,propertyTwo,Boolean isOperative)。

有什么想法吗?

谢谢!

1 个答案:

答案 0 :(得分:0)

我使用ViewHolder找到了解决方案:

@Override
public View getView(final int position, View convertView, ViewGroup parent) {
    ViewHolder holder;
    if (convertView == null) {
        holder = new ViewHolder();
        convertView = LayoutInflater.from(mContext).inflate(R.layout.listview_item, null);
        holder.layoutOperative = convertView.findViewById(R.id.layout_list_item);
        holder.txtOne = convertView.findViewById(R.id.text_one);
        holder.txtTwo = convertView.findViewById(R.id.text_two);
        convertView.setTag(holder);
    } else {
        holder = (ViewHolder) convertView.getTag();
    }

    if (mBuildingsList.get(position).isOperative()) {
        holder.layoutOperative.setBackgroundResource(R.drawable.list_item_background_active);
    } else {
        holder.layoutOperative.setBackgroundResource(R.drawable.list_item_background_inactive);
    }

    holder.txtOne.setText(mList.get(position).getPropertyOne());
    holder.txtTwo.setText(mList.get(position).getPropertyTwo());

    return convertView;

}

谢谢大家!