gpt4 book ai didi

android - ListView Item 位置切换和滚动时的干扰

转载 作者:太空狗 更新时间:2023-10-29 16:39:09 24 4
gpt4 key购买 nike

我正在使用 ListView 和 BaseAdapter 来填充列表项。我只是制作一个简单的聊天应用程序,自己的消息显示在右侧,好友消息显示在左侧。

问题是当我滚动列表以查看上面的项目时,其余的会受到干扰,比如自己的消息在右侧,有些在左侧。

滚动前

   Friend
Me
Friend
Me
Friend
Me

滚动后

   Friend
Me
Friend
Me
Friend
Me
Friend
Me

这是我的 BaseAdapter 代码

    @Override
public View getView(int position, View convertView, ViewGroup parent) {
View rowView = convertView;
if (rowView == null) {
LayoutInflater inflater = LayoutInflater.from(context);
if (names.get(position).equals(own)){
rowView = inflater.inflate(R.layout.list_item_chat_message_own,
null);}
else{
rowView = inflater.inflate(
R.layout.list_item_chat_message_contact, null);

}
ViewHolder viewHolder = new ViewHolder();
viewHolder.name = (TextView) rowView.findViewById(R.id.name);
viewHolder.message=(TextView) rowView.findViewById(R.id.firstLine);
rowView.setTag(viewHolder);
}

ViewHolder holder = (ViewHolder) rowView.getTag();
String name = names.get(position);
String message = messages.get(position);
//Log.e("name", own+"-"+name);
//Log.e("message", message);
holder.message.setTextColor(context.getResources().getColor(this.getTextColorID()));

if(name.equals(own))
holder.name.setText("Me");
else
holder.name.setText(name);
holder.message.setText(message);

return rowView;
}

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

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

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

最佳答案

您必须在适配器中实现 getItemViewType(position)getViewTypeCount 方法。

第一个告诉适配器在给定位置需要使用哪种类型的行,第二个告诉适配器它需要使用多少行类型

更新:

应该是这样的:

@Override
public int getViewTypeCount() {
// you have two different row types
return 2;
}

@Override
public int getItemViewType(int position) {
// You need to tell to adapter which row is needed at given position
return names.get(position).equals(own) ? 0 : 1;
}

public View getView(int position, View convertView, ViewGroup parent) {
View rowView = convertView;
if (rowView == null) {
LayoutInflater inflater = LayoutInflater.from(context);
if (getItemViewType(position) == 0){
rowView = inflater.inflate(R.layout.list_item_chat_message_own,
null);}
else{
rowView = inflater.inflate(
R.layout.list_item_chat_message_contact, null);

}
// rest of your code
}
//rest of your code
}

关于android - ListView Item 位置切换和滚动时的干扰,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21101155/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com