列表视图滚动时滞后,并添加项目时崩溃

我有一个自定义列表视图与一个按钮来添加更多元素 但当我添加和元素的应用程序崩溃,但是当我重新启动时,我发现该元素添加,(很少它不会崩溃)列表视图滚动时滞后,并添加项目时崩溃

而且我

我使用自定义适配器

class CustomAdapter extends BaseAdapter { 

ArrayList<ListItem> listItems = new ArrayList<ListItem>();

CustomAdapter(ArrayList<ListItem> list){

this.listItems = list;

}

@Override

public int getCount() {

return listItems.size();

}

@Override

public Object getItem(int position) {

return listItems.get(position).name;

}

@Override

public long getItemId(int position) {

return position;

}

@Override

public View getView(int i, View convertView, ViewGroup parent) {

LayoutInflater inflater = getLayoutInflater();

View view = inflater.inflate(R.layout.list_item,null);

TextView name = (TextView) view.findViewById(R.id.name);

TextView lastm = (TextView) view.findViewById(R.id.last);

TextView time = (TextView) view.findViewById(R.id.time);

CircleImageView pic= (CircleImageView) view.findViewById(R.id.pic);

name.setText(listItems.get(i).name);

lastm.setText(listItems.get(i).lastm);

time.setText(listItems.get(i).time);

Bitmap bmp = BitmapFactory.decodeByteArray(listItems.get(i).pic,0,listItems.get(i).pic.length);

pic.setImageBitmap(bmp);

return view;

}

}

,当我添加元素的应用crashs

add.setOnClickListener(new View.OnClickListener() { 

@Override

public void onClick(View v) {

EditText editText=(EditText) mView.findViewById(R.id.name);

String name=editText.getText().toString();

boolean result=myDataBase.insertData(imageViewToByte(img),name,"no messages yet","");

if (result) {

Toast.makeText(Main2Activity.this, "Saved in DATABASE", Toast.LENGTH_SHORT).show();

viewLastData();

dialog.dismiss();

}

回答:

如果您的ListView滞后,那是因为您使用wrap_content作为listView的layout_height。它强制你的ListView计算所有内部项目,并且它有巨大的性能影响。

所以用match_parent替换wrap_content以避免这些滞后。

编辑:在你的Adapter使用ViewHolder模式也看到this link。

下面是一个例子:

// ViewHolder Pattern 

private static class ViewHolder {

TextView name, status;

}

@Override @NonNull

public View getView(int position, View convertView, @NonNull ViewGroup parent) {

ViewHolder holder;

if (convertView == null) {

LayoutInflater vi = LayoutInflater.from(getContext());

convertView = vi.inflate(R.layout.list_item, parent, false);

holder = new ViewHolder();

holder.name = (TextView) convertView.findViewById(R.id.text_name);

holder.status = (TextView) convertView.findViewById(R.id.another_text);

convertView.setTag(holder);

} else {

holder = (ViewHolder) convertView.getTag();

}

// Then do the other stuff with your item

// to populate your listView

// ...

return convertView

}

以上是 列表视图滚动时滞后,并添加项目时崩溃 的全部内容, 来源链接: utcz.com/qa/265778.html

回到顶部