2

Уже почти год мне никак не поддаётся ListView. Для меня это очень сложный виджет, постоянные проблемы и нервы с багами во время прокрутки. Много статей как на русском, так и английском перечитаны. Народ, обьясните хоть вы, раз и навсегда, как правильно организовать адаптер? Делаю чат, все шло ровно, как только дело дошло до тестирования, появились нехорошие отзывы, при прокрутке сообщения живут своей жизнью - нет бы встать на месте, они меняются данными, например ником отправителя, текстом сообщения, временем отправки. Дайте мне МАКСИМАЛЬНУЮ критику, уже не могу так жить. Код...

public class CustomAdapter extends BaseAdapter
{
    ArrayList<HashMap<String, String>> adapterList;
    LayoutInflater mInflater;
    int type;

    public CustomAdapter(List<? extends Map<String, String>> dat)
    {
        adapterList = (ArrayList<HashMap<String, String>>) dat;
        mInflater = (LayoutInflater)context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
    }

    @Override
    public int getCount()
    {
        return adapterList.size();
    }

    @Override
    public Object getItem(int position)
    {
        return adapterList.get(position);
    }

    @Override
    public long getItemId(int position)
    {
        return position;
    }


    @Override
    public int getItemViewType(int position) {
        if (adapterList.get(position).get("author").equals(nick)) 
             type = 0;
        else type = 1;
        return type;
    }

    @Override
    public int getViewTypeCount() {
    return 2;
    }

    @Override
    public View getView(int position, View v, final ViewGroup parent)
    {
        if(v==null){
        v = mInflater.inflate((getItemViewType(position)==0) ? R.layout.item_right : R.layout.item_left, null);


        HashMap<String,String> fast_parse = adapterList.get(position);
        String author_str = fast_parse.get("author");
        String client_str = fast_parse.get("client");
        String text_str = fast_parse.get("text");
        String data_str = fast_parse.get("data");
        TextView tv_full_author = (TextView)v.findViewById(R.id.full_nick);
        TextView tv_circle_author = (TextView)v.findViewById(R.id.first_char_nick);
        TextView tv_client = (TextView)v.findViewById(R.id.reply_marker);
        TextView tv_text = (TextView)v.findViewById(R.id.message);
        TextView tv_data = (TextView)v.findViewById(R.id.time);
        tv_full_author.setText(author_str);
        tv_circle_author.setText(author_str.substring(0,1));
        if(!client_str.equals("0"))
        {
            tv_client.setVisibility(View.VISIBLE);
            tv_client.setText(client_str+",");

            if(client_str.equals(nick)&&(getItemViewType(position)==1))
            {
                tv_client.setTextColor(Color.parseColor("#A40dff"));
            }
        }
        tv_text.setText(text_str);
        tv_data.setText(data_str);
        }
        return v;
    }
}

UPD

От сервера мне приходит JSON с сообщениями, я его парсю и в HashMap отправляю в адаптер. Разметки две - правая для своих сообщений, левая для чужих. В случае если отправителем сообщения являешься ты используется правая разметка, иначе левая. Если обращение к тебе, оно выделяется цветом

UPD - CODE 1

Добавил каждому if-у свой else, но не помогло

public class CustomAdapter extends BaseAdapter
{
    ArrayList<HashMap<String, String>> adapterList;
    LayoutInflater mInflater;
    int type;

    public CustomAdapter(List<? extends Map<String, String>> dat)
    {
        adapterList = (ArrayList<HashMap<String, String>>) dat;
        mInflater = (LayoutInflater)context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
    }

    @Override
    public int getCount()
    {
        return adapterList.size();
    }

    @Override
    public Object getItem(int position)
    {
        return adapterList.get(position);
    }

    @Override
    public long getItemId(int position)
    {
        return position;
    }


    @Override
    public int getItemViewType(int position) {
        if (adapterList.get(position).get("author").equals(nick)) 
             type = 0;
        else type = 1;
        return type;
    }

    @Override
    public int getViewTypeCount() {
    return 2;
    }

    @Override
    public View getView(int position, View v, final ViewGroup parent)
    {
        if(v==null){
        v = mInflater.inflate((getItemViewType(position)==0) ? R.layout.item_right : R.layout.item_left, null);


        HashMap<String,String> fast_parse = adapterList.get(position);
        String author_str = fast_parse.get("author");
        String client_str = fast_parse.get("client");
        String text_str = fast_parse.get("text");
        String data_str = fast_parse.get("data");
        TextView tv_full_author = (TextView)v.findViewById(R.id.full_nick);
        TextView tv_circle_author = (TextView)v.findViewById(R.id.first_char_nick);
        TextView tv_client = (TextView)v.findViewById(R.id.reply_marker);
        TextView tv_text = (TextView)v.findViewById(R.id.message);
        TextView tv_data = (TextView)v.findViewById(R.id.time);
        tv_full_author.setText(author_str);
        tv_circle_author.setText(author_str.substring(0,1));
        if(!client_str.equals("0")){
            tv_client.setVisibility(View.VISIBLE);
            tv_client.setText(client_str+",");

            if(client_str.equals(nick)&&(getItemViewType(position)==1))
tv_client.setTextColor(Color.parseColor("#A40dff"));
else tv_client.setTextColor(Color.BLACK);
        }
        else{
            tv_client.setText("");
            tv_client.setVisibility(View.GONE);
        }
        tv_text.setText(text_str);
        tv_data.setText(data_str);
        }
        return v;
    }
}

UPD - CODE 2

Работает! А я пошел учить холдер.

public class CustomAdapter extends BaseAdapter
{
    ArrayList<HashMap<String, String>> adapterList;
    LayoutInflater mInflater;
    int type;

    public CustomAdapter(List<? extends Map<String, String>> dat)
    {
        adapterList = (ArrayList<HashMap<String, String>>) dat;
        mInflater = (LayoutInflater)context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
    }

    @Override
    public int getCount()
    {
        return adapterList.size();
    }

    @Override
    public Object getItem(int position)
    {
        return adapterList.get(position);
    }

    @Override
    public long getItemId(int position)
    {
        return position;
    }


    @Override
    public int getItemViewType(int position) {
        if (adapterList.get(position).get("author").equals(nick)) 
             type = 0;
        else type = 1;
        return type;
    }

    @Override
    public int getViewTypeCount() {
    return 2;
    }

    @Override
    public View getView(int position, View v, final ViewGroup parent)
    {
        if(v==null)
        v = mInflater.inflate((getItemViewType(position)==0) ? R.layout.item_right : R.layout.item_left, null);


        HashMap<String,String> fast_parse = adapterList.get(position);
        String author_str = fast_parse.get("author");
        String client_str = fast_parse.get("client");
        String text_str = fast_parse.get("text");
        String data_str = fast_parse.get("data");
        TextView tv_full_author = (TextView)v.findViewById(R.id.full_nick);
        TextView tv_circle_author = (TextView)v.findViewById(R.id.first_char_nick);
        TextView tv_client = (TextView)v.findViewById(R.id.reply_marker);
        TextView tv_text = (TextView)v.findViewById(R.id.message);
        TextView tv_data = (TextView)v.findViewById(R.id.time);
        tv_full_author.setText(author_str);
        tv_circle_author.setText(author_str.substring(0,1));
        if(!client_str.equals("0"))
        {
            tv_client.setVisibility(View.VISIBLE);
            tv_client.setText(client_str+",");

            if(client_str.equals(nick)&&(getItemViewType(position)==1))
            {
                tv_client.setTextColor(Color.parseColor("#A40dff"));
            }
            else{
                tv_client.setTextColor(Color.BLACK);
            }
        }
        else{
            tv_client.setText("");
            tv_client.setVisibility(View.GONE);
        }
        tv_text.setText(text_str);
        tv_data.setText(data_str);

        return v;
    }
}
3
  • 3
    1) много статей перечитали, то где ViewHolder, о нем же в каждой статье о адаптерах к ListView упоминают. 2) не забывайте о том что элементы переиспользуются, т.е. к вам в getView прилетит элемент уже вышедший за границы экрана - если кратко, то на любой if должен быть else
    – ermak0ff
    28 сен 2016 в 14:29
  • 2
    то есть если в if'e есть tv_client.setVisibility(View.VISIBLE);, то в else'e должно быть tv_client.setVisibility(View.INVISIBLE); так же и для ифа с цветом, добавить цвет по дефолту
    – ermak0ff
    28 сен 2016 в 14:35
  • Комментарии не предназначены для расширенной дискуссии; разговор перемещен в чат.
    – user177221
    9 окт 2016 в 10:10

1 ответ 1

3

Проблема в том что, что данное условие сформировано не верно:

    if(v==null){
        ...
    }
    return v;

Получается что если v не равно null(что будет происходить при прокрутке ListView в связи с переиспользованием item'ов), то оно не будет заполнятся информацией соответствующей позиции элемента.

Следовательно заполнение v информацией необходимо вынести из условия.

Ваш ответ

By clicking “Отправить ответ”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.