【问题标题】:getView() not working properlygetView() 无法正常工作
【发布时间】:2012-12-27 17:05:37
【问题描述】:

看代码:-

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

    View row = convertView;

    if (row == null) {
        LayoutInflater inflater = ((Activity)  mContext).getLayoutInflater();
        row = inflater.inflate(R.layout.country_row, parent, false);
    }

    return row;
}

国家行 XML 是:--

<?xml version="1.0" encoding="utf-8"?>

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
  android:layout_width="fill_parent"
  android:layout_height="match_parent"
  android:orientation="horizontal"
  android:weightSum="1" >

<TextView
    android:id="@+id/nameOfCountry"
    android:layout_width="0dp"
    android:layout_height="wrap_content"
    android:layout_weight="0.8"
    android:text="Country" />

<CheckBox
    android:id="@+id/checkBox"
    android:layout_width="0dp"
    android:layout_height="wrap_content"
    android:layout_weight="0.2"
    android:gravity="right" />

现在我的问题是,一旦我选中列表视图中的几个复选框并滚动列表视图,就会自动选中许多其他复选框......

我知道 getView 有问题,但我不知道在哪里......

如果我不重用转换视图,问题也会得到解决。但这是一个愚蠢的想法......

任何想法.....

【问题讨论】:

  • 阅读关于视图回收的信息。重用视图时需要设置右行的属性。

标签: android listview android-listview listadapter


【解决方案1】:

那是因为 ListView 会回收视图。从本质上讲,它重用了一些屏幕外的视图,使新的视图出现在屏幕上以帮助提高性能。有两种处理方法:

  1. 在返回行之前设置视图的值。例如,您将设置nameOfCountry 以及是否在return view 行之前选中复选框。不过,要做到这一点,您需要跟踪检查的内容。

  2. 不要使用convertview,而是每次都扩充一个新视图。这可能会导致性能下降,但只要列表不太长,它就不应该太引人注目(至少根据我的经验)。只需忽略convertview

【讨论】:

  • 您正在使用/扩展什么类型的适配器? BaseAdapter,ArrayAdapter?
  • 您还需要示例代码吗?如果你愿意,我可以放一些。
  • 嗯,我做了一些我想做的事情,但是如果你能分享一些代码,我会很感激...... :)
【解决方案2】:

如果您重复使用旧的View,则必须明确设置复选框的状态。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-12-01
    • 1970-01-01
    • 1970-01-01
    • 2016-09-01
    • 2012-07-11
    • 2018-04-08
    • 2017-04-20
    相关资源
    最近更新 更多