android ListView使用注意事项

总结本人在使用android Listview时遇到的一些应该注意的事项:

1.想要将listview item项里的子控件的点击事件交给item来处理,需要两步:

(1)重写子控件的onTouchEvent方法

@Override
public boolean onTouchEvent(MotionEvent event) {
// TODO Auto-generated method stub
return false;
}

(2)在item的xml文件中的根布局加上一句:

android:descendantFocusability="blocksDescendants" 
2.listview优化策略viewholder,代码举例如下:

class MyAdapter extends BaseAdapter{
Context mContext;
LinearLayout linearLayout = null;
LayoutInflater inflater;
TextView tex;
final int VIEW_TYPE = 2;
final int TYPE_1 = 0;
final int TYPE_2 = 1;

public MyAdapter(Context context) {
mContext = context;
inflater = LayoutInflater.from(mContext);
}

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

//每个convert view都会调用此方法,获得当前所需要的view样式
@Override
public int getItemViewType(int position) {
int p = position%6;
if(p == 0)
return TYPE_1;
else if(p < 3)
return TYPE_2;
else
return TYPE_1;
}

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

@Override
public Object getItem(int arg0) {
return listString.get(arg0);
}

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

@Override
public View getView(int position, View convertView, ViewGroup parent) {
viewHolder1 holder1 = null;
viewHolder2 holder2 = null;
int type = getItemViewType(position);

//无convertView,需要new出各个控件
if(convertView == null)
{
//按当前所需的样式,确定new的布局
switch(type)
{
case TYPE_1:
convertView = inflater.inflate(R.layout.listitem1, parent, false);
holder1 = new viewHolder1();
holder1.textView = (TextView)convertView.findViewById(R.id.textview1);
holder1.checkBox = (CheckBox)convertView.findViewById(R.id.checkbox);
convertView.setTag(holder1);
break;
case TYPE_2:
convertView = inflater.inflate(R.layout.listitem2, parent, false);
holder2 = new viewHolder2();
holder2.textView = (TextView)convertView.findViewById(R.id.textview2);
holder2.imageView = (ImageView)convertView.findViewById(R.id.imageview);
convertView.setTag(holder2);
break;
}
}
else
{
//有convertView,按样式,取得不用的布局
switch(type)
{
case TYPE_1:
holder1 = (viewHolder1) convertView.getTag();
break;
case TYPE_2:
holder2 = (viewHolder2) convertView.getTag();
break;
}
//设置资源
switch(type)
{
case TYPE_1:
holder1.textView.setText(Integer.toString(position));
holder1.checkBox.setChecked(true);
break;
case TYPE_2:
holder2.textView.setText(Integer.toString(position));
holder2.imageView.setBackgroundResource(R.drawable.icon);
break;
}
}
return convertView;
}
}
//各个布局的控件资源
static class viewHolder1{
CheckBox checkBox;
TextView textView;
}
static class viewHolder2{
ImageView imageView;
TextView textView;
} 

3.Listview中子控件的监听事件需要在adapter的getview方法中编写,而尽量不要在activity里写。如果在需要在getview中要用到viewholder则viewholder的编写方式应与原来常见的编写方式不同。不应出现如下部分内容:

if (view == null) {

...

} else

{

holder = (ViewHolder) view.getTag();

...

}

郑重声明:本站内容如果来自互联网及其他传播媒体,其版权均属原媒体及文章作者所有。转载目的在于传递更多信息及用于网络分享,并不代表本站赞同其观点和对其真实性负责,也不构成任何其他建议。