每次滚动时都会调用CustomAdapter getView()

时间:2015-08-31 07:43:09

标签: android listview android-listview custom-adapter

每次向上或向下滚动时,都会调用getView()中的CustomAdapter方法。

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

    View vi = convertView;
    ViewHolder holder;
    if (convertView == null) {
        vi = inflater.inflate(R.layout.projectlist, null);

        holder = new ViewHolder();
        holder.projectTitelTextView = (TextView) vi.findViewById(R.id.projectTitle);
        holder.projectInfoTextView = (TextView) vi.findViewById(R.id.projectInfo);
        holder.projectImageImageView = (ImageView) vi.findViewById(R.id.projectImage);
        holder.projectDeadline = (TextView) vi.findViewById(R.id.projectdeadline);

        vi.setTag(holder);
    } else {
        holder = (ViewHolder) vi.getTag();
    }
    if (projectItems.size() <= 0) {
        [...]
    } else {
         [...]
        }
    }
    return vi;
}

ListView XML:

<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools" android:id="@+id/container"
android:layout_width="match_parent" android:layout_height="match_parent"
tools:context=".MainActivity" tools:ignore="MergeRootFrame">

<LinearLayout
    android:orientation="horizontal"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    >

    <ListView android:id="@+id/android:list"
        android:layout_width="wrap_content"
        android:layout_height="fill_parent"
        android:focusable="false"
        android:clickable="false"
        android:smoothScrollbar="true" />

</LinearLayout>

为什么每次向上或向下滚动时都会调用它? 假设我显示了10个项目。如果我向下滚动,getView()调用一次,它会再显示一个项目。如果我硬滚动并想要到列表的末尾。它被多次调用,直到加载并显示数据。

如果我想向上滚动,则会出现相同的情况。

我可以做些什么来防止多次调用getView()或者是否有必要?

亲切的问候

3 个答案:

答案 0 :(得分:4)

这就是ListAdapters的工作方式。每当需要创建新的列表项时,或者至少在需要使用特定位置的数据更新列表项时,都会使用getView()

答案 1 :(得分:0)

建议RomainGuy

  

这不是问题,订单绝对没有保证   getView()将被调用多少次。

ListView适配器的常规行为是多次调用getView()方法。

答案 2 :(得分:-1)

如果滚动你没有必要改变一些东西,请尝试类似的东西。

boolean fisttime = true;

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

if(position == 0 && isFirstRun) {
    View vi = convertView;
ViewHolder holder;
if (convertView == null) {
    vi = inflater.inflate(R.layout.projectlist, null);

    holder = new ViewHolder();
    holder.projectTitelTextView = (TextView) vi.findViewById(R.id.projectTitle);
    holder.projectInfoTextView = (TextView) vi.findViewById(R.id.projectInfo);
    holder.projectImageImageView = (ImageView) vi.findViewById(R.id.projectImage);
    holder.projectDeadline = (TextView) vi.findViewById(R.id.projectdeadline);

    vi.setTag(holder);
} else {
    holder = (ViewHolder) vi.getTag();
}
if (projectItems.size() <= 0) {
    [...]
} else {
     [...]
    }
}
return vi;
}

}

相关问题