listview这个控件在Android的开发过程中运用得比较广泛,本意是用作展示数据,但在实际的开发过程中却可能和button,edittext等合用,那就会涉及到焦点问题,edittext展示错位的问题。在前段时间的项目开发中,自己也遇到了这些情况,自己也上网查了一些方法,也总结了自己的方法。
先来说说在网上查到的方法吧,就是通过标签来为每个item标明一个数据类,然后通过gettag取出数据类,然后改变其中的变量值。
代码如下:
class MyAdapter extends BaseAdapter(){
private Context context;
private List<Msg> msg = new ArrayList<Msg>();
public class Message{
EditText edit;
public Message(View v){
edit = v.findViewById();
}
}
public MyAdapter(Context context){
this.context = context;
}
public int getCount(){
return msg.size();
}
public Object getItem(int arg0){
return null;
}
public long getItemId(int arg0){
return null;
}
public View getView(int arg0,View arg1,ViewGroup arg2){
final Message m;
Msg ms = msg.get(arg0);
if(arg1 == null){
arg1 = LayoutInflater.from(context).inflater();
m = new Msg(arg1);
arg1.setTag(m);
}else{
m = (Message)arg1.getTag();
}
ms.edit.setTag(ms);
ms.edit.setText();
}
}
相信大家对listview会出现错位的现象的原因也有百度过吧,就是复用,那其实解决这个问题的办法简单粗暴一点就是把你要展示信息和position对应起来,我通过打印日志看出,界面展示出来的item和position是不一致的,也就是说,item会被复用,但position可以用作对应的标识。所以,我们可以把每个position值和数据类对应起来。
代码如下:
class MyAdapter extends BaseAdapter(){
private Context context;
private List<Msg> msg = new ArrayList<Msg>();
public class Message{
EditText edit;
int id;
public Message(View v){
edit = v.findViewById();
}
}
public MyAdapter(Context context){
this.context = context;
}
public int getCount(){
return msg.size();
}
public Object getItem(int arg0){
return null;
}
public long getItemId(int arg0){
return null;
}
public View getView(int arg0,View arg1,ViewGroup arg2){
final Message m;
if(arg1 == null){
arg1 = LayoutInflater.from(context).inflater();
m = new Msg(arg1);
arg1.setTag(m);
}else{
m = (Message)arg1.getTag();
}
m.id = arg0;
ms.edit.setText();
}
}
自己试验过没有错误