Android Listview:第一个元素中的imageview
我在聊天应用程序中有一个自定义列表视图。它显示了一些我已经与之交谈过的人。我希望listview中的第一个元素是imageview,单击该元素时,用户有机会键入他想要聊天的新用户。我已经实现了这一点(我不想使用ListView标题),通过向ListView添加一个元素,然后根据位置膨胀imageview或textviewAndroid Listview:第一个元素中的imageview,android,listview,android-listview,Android,Listview,Android Listview,我在聊天应用程序中有一个自定义列表视图。它显示了一些我已经与之交谈过的人。我希望listview中的第一个元素是imageview,单击该元素时,用户有机会键入他想要聊天的新用户。我已经实现了这一点(我不想使用ListView标题),通过向ListView添加一个元素,然后根据位置膨胀imageview或textview View v = convertView; if (v == null) { LayoutInflater vi; vi = Layo
View v = convertView;
if (v == null) {
LayoutInflater vi;
vi = LayoutInflater.from(getContext());
if (position == 0)
v = vi.inflate(R.layout.list_item_chat_list_header, parent, false);
else
v = vi.inflate(R.layout.list_item_chat_list, parent, false);
}
TextView tvName = ((TextView) v.findViewById(R.id.id_chat_list_name));
TextView tvPreview = ((TextView) v.findViewById(R.id.id_chat_list_preview));
if ( tvName != null && tvPreview != null ) {
ChatListElement p = getItem(position);
tvName.setText(p.name);
String preview = p.lastMessage;
if (preview.length() > 30)
preview = preview.substring(0, 30) + "...";
tvPreview.setText(preview);
}
return v;
但是,当我运行它时,中间的一些视图也变成了图像。我认为这与listview中回收的视图有关,但我不知道如何使其工作。
非常感谢您步骤#1:在适配器中重写getViewTypeCount()
以返回2
步骤2:覆盖适配器中的getItemViewType()
,为位置0
(您的ImageView
)返回0
,为其他所有(正常行)返回1
步骤3:使用getLayoutInflater()
,在活动中调用,而不是LayoutInflater.from()
(在技术上与您的问题无关,但稍后您将感谢我帮助确保自定义主题按预期工作)
步骤#1和#2将教会列表视图
维护两个对象池,每种类型的行一个,并确保回收的行的类型与请求的位置相符。询问了无数次…=>适配器回收视图