Как установить изображение в imageview внутри ListView в Android? - PullRequest
1 голос
/ 26 мая 2010

У меня есть просмотр списка, который включает 2 просмотра текста и 1 просмотр изображения. Теперь изображение в режиме просмотра изображений будет установлено при определенных условиях, в противном случае его следует оставить пустым без изображения.

Проблема в том, что изображения не располагаются в правильных строках. Скажем, например, изображение должно отображаться в строке 3, но оно должно отображаться в строке 4. И в некоторых случаях в каждой строке будет одно и то же изображение.

Кто-нибудь сталкивался с такой проблемой? Я действительно ничего не понимаю о причине этого. Кто-нибудь может указать на проблему?


private static class VilleAdapter extends BaseAdapter {
    private LayoutInflater mInflater = null;

    // private Context context = null;

    public VilleAdapter(Context context) {
        // Cache the LayoutInflate to avoid asking for a new one each time.
        mInflater = LayoutInflater.from(context);
    }

    /**
     * The number of items in the list is determined by the number of
     * speeches in our array.
     * 
     * @see android.widget.ListAdapter#getCount()
     */
    public int getCount() {
        // return BabbleMainListParse.getNumOfBabbles();
        return VilleMainListParse.getVilleCount();
    }

    /**
     * Since the data comes from an array, just returning the index is
     * sufficent to get at the data. If we were using a more complex data
     * structure, we would return whatever object represents one row in the
     * list.
     * 
     * @see android.widget.ListAdapter#getItem(int)
     */
    public Object getItem(int position) {
        return position;
    }

    /**
     * Use the array index as a unique id.
     * 
     * @see android.widget.ListAdapter#getItemId(int)
     */
    public long getItemId(int position) {
        return position;
    }

    /**
     * Make a view to hold each row.
     * 
     * @see android.widget.ListAdapter#getView(int, android.view.View,
     *      android.view.ViewGroup)
     */
    public View getView(int position, View convertView, ViewGroup parent) 
    {
        // A ViewHolder keeps references to children views to avoid
        // unneccessary calls
        // to findViewById() on each row.
        ViewHolder holder;

        // When convertView is not null, we can reuse it directly, there is
        // no need
        // to reinflate it. We only inflate a new View when the convertView
        // supplied
        // by ListView is null.
        if (convertView == null) 
        {
            convertView = mInflater.inflate(R.layout.villerow, parent,false);

            // Creates a ViewHolder and store references to the two children
            // views
            // we want to bind data to.
            holder = new ViewHolder();
            holder.txtVilleListTitle = (TextView) convertView.findViewById(R.id.txtVilleListTitle);
            holder.txtVilleDescription = (TextView) convertView.findViewById(R.id.txtVilleDescription);
            holder.imgvillepwd = (ImageView) convertView.findViewById(R.id.imgvillepwd);

            convertView.setTag(holder);
        }
        else 
        {
            // Get the ViewHolder back to get fast access to the TextView
            holder = (ViewHolder) convertView.getTag();
        }

        // Bind the data efficiently with the holder.
        holder.txtVilleListTitle.setText(VilleMainListParse.getMsgTitle(position));

        if(VilleMainListParse.getMsgDesc(position).length() > 30)
        {
            String temp = VilleMainListParse.getMsgDesc(position).substring(0, 30);
            temp = temp +".....";
            holder.txtVilleDescription.setText(temp);
        }
        else
            holder.txtVilleDescription.setText(VilleMainListParse.getMsgDesc(position));

        if(!VilleMainListParse.getPwd(position).equals(""))
        {
            if(VilleMainListParse.getUnlock(position))
            {
                holder.imgvillepwd.setBackgroundResource(R.drawable.lock);
            }   
            else if(!VilleMainListParse.getUnlock(position))
            {
                holder.imgvillepwd.setBackgroundResource(R.drawable.lock_open);
            }
        }

        return convertView;
    }

    static class ViewHolder
    {
        TextView txtVilleListTitle;
        TextView txtVilleDescription;
        ImageView imgvillepwd;
    }
}

Приведенный выше код относится только к адаптеру. Сначала появляется экран входа в систему, когда нажимается кнопка входа в систему, данные загружаются из Интернета, а затем этот список просмотра загружается с этими данными. Эти данные изначально загружены правильно.

Может кто-нибудь сообщить мне, в чем проблема с этим кодом?

Ответы [ 2 ]

1 голос
/ 26 мая 2010

Поскольку вы повторно используете те же виды, вы должны очистить изображение, если оно не должно отображаться. В противном случае предыдущая картинка будет отображаться там. Поэтому я предлагаю следующее исправление:

if(!VilleMainListParse.getPwd(position).equals(""))
{
    if(VilleMainListParse.getUnlock(position))
    {
        holder.imgvillepwd.setBackgroundResource(R.drawable.lock);
    }   
    else if(!VilleMainListParse.getUnlock(position))
    {
        holder.imgvillepwd.setBackgroundResource(R.drawable.lock_open);
    }
}
else
    holder.imgvillepwd.setBackgroundDrawable(null);
0 голосов
/ 26 мая 2010

Вы можете также рассмотреть возможность использования методов setImageResource / setImageBitmap вместо setBackgroundXxx.

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...