【问题标题】:Custom row elements in ListFragment are displaying incorrectly after scrollingListFragment 中的自定义行元素在滚动后显示不正确
【发布时间】:2012-08-19 06:23:26
【问题描述】:

我有一个ListFragment,其中包含使用自定义ArrayAdapter 填充的Earthquake 对象列表。每个元素要么被“突出显示”,要么取决于地震的震级是否高于某个值。问题是滚动后,“突出显示”的行颜色将应用于其他行。我怀疑这与ListView 中使用的缓存有关。我怎样才能防止这种情况发生?

这是我的EarthquakeArrayAdapter 类的getView 方法:

public View getView(int position, View convertView, ViewGroup parent) {
    if (convertView == null) {
        convertView = mInflater.inflate(R.layout.row, parent, false);
    }

    Earthquake quake = mQuakes.get(position);
    if (quake != null) {
        TextView itemView = (TextView) convertView.findViewById(R.id.magnitude);
        if (itemView != null) {
            itemView.setText(quake.getFormattedMagnitude());
            if (quake.getRoundedMagnitude() >= mMinHighlight)
                itemView.setTextColor(Color.RED);
        }
    // Set other views in the layout, no problems here...
    }
    return convertView;
}

这是我的row.xml 布局文件:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="horizontal" >

    <TextView
       android:id="@+id/magnitude"
       style="@style/ListFont.Magnitude" />

    <LinearLayout
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:orientation="vertical" >
        <TextView
            android:id="@+id/date"
            style="@style/ListFont.NonMagnitude"
            android:gravity="center_horizontal|top"
            android:textSize="18sp" />
        <TextView
            android:id="@+id/location"
            style="@style/ListFont.NonMagnitude"
            android:gravity="center_horizontal|bottom"
            android:textSize="14sp" />
    </LinearLayout>

</LinearLayout>

我在 ListView 小部件上观看了 this 视频,我正在考虑按照 Adam Powell 最后的建议 - 在 ScrollView 中动态填充和扩展 LinearLayout 并简单地使用它。我的数据目前介于 0 到 30 个项目之间(我尚未对此进行测试,因此不知道性能差异可能是什么)。但是,这些界限可能并不总是保持不变 - 所以如果可以的话,我想解决这个问题。

【问题讨论】:

    标签: android android-listview android-listfragment


    【解决方案1】:

    如果通过突出显示您的意思是在幅度 TextView 上设置颜色,那么如果幅度不是所需的,您只需还原任何更改:

    if (quake.getRoundedMagnitude() >= mMinHighlight) {
         itemView.setTextColor(Color.RED);
    } else {
         itemView.setTextColor(/*the default color*/);
    } 
    

    【讨论】:

    • 嗯,这是一个非常简单的解决方案。为什么我的原始代码在第一次绘制时工作,然后在项目滚动时更改?我会认为不设置文本颜色(即,将其保留为默认颜色)等同于显式指定默认颜色。
    • @adamsp 您的代码一开始可以工作,因为不涉及回收的行。只要您滚动ListView,它就可以回收之前的一些行以重用它们以提高性能。例如,第一个位置是红色,您滚动列表。当需要显示新行时,ListView 可以重用第一行并将其显示为新行(红色仍然存在,因为您不还原它)。因此,如果当前行不满足某些条件,则应始终将该行置于默认状态(例如,没有红色)。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-07-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多