Уже почти год мне никак не поддаётся 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;
}
}
ViewHolder
, о нем же в каждой статье о адаптерах кListView
упоминают. 2) не забывайте о том что элементы переиспользуются, т.е. к вам вgetView
прилетит элемент уже вышедший за границы экрана - если кратко, то на любойif
должен бытьelse
if
'e естьtv_client.setVisibility(View.VISIBLE);
, то вelse
'e должно бытьtv_client.setVisibility(View.INVISIBLE);
так же и для ифа с цветом, добавить цвет по дефолту