Android 自定义 ArrayAdapter 不停留在滚动条上

标签 android android-layout listview customization android-arrayadapter

我创建了一个自定义的ArrayAdapter(代码如下),在滚动之前它工作得很好。一旦我滚动所有项目就会变成绿色,我一直在抓着我的头发试图找出原因。任何帮助将不胜感激。

自定义适配器旨在使任何 ListView 项目的文本长度为 3 个字符 变为绿色,而所有其他颜色应保持默认的黑色。

public class FoundAdapter extends ArrayAdapter<String> {

  private final Activity context;
  private final ArrayList<String> names;

  static class ViewHolder {
    public TextView text;
  }

  public FoundAdapter(Activity context, ArrayList<String> names) {
    super(context, R.layout.found, names);
    this.context = context;
    this.names = names;
  }

  @Override
  public View getView(int position, View convertView, ViewGroup parent) {
    View rowView = convertView;
    if (rowView == null) {
      LayoutInflater inflater = context.getLayoutInflater();
      rowView = inflater.inflate(R.layout.found, null);
      ViewHolder viewHolder = new ViewHolder();
      viewHolder.text = (TextView) rowView.findViewById(R.id.found_txt);
      rowView.setTag(viewHolder);
    }

    ViewHolder holder = (ViewHolder) rowView.getTag();
    String s = names.get(position);
    if(s.length()==3) {
        holder.text.setTextColor(0xFF008B45); //green
    }
    holder.text.setText(s);

    return rowView;
  }
} 

通过以下方式在 .java 代码中调用:

adapter=new FoundAdapter(this, array);      
ListView view = (ListView) findViewById(R.id.list);
view.setAdapter(adapter);

R.layout.found:

<?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="wrap_content"
android:orientation="horizontal">

<TextView 
    android:id="@+id/found_txt"
  android:layout_width="wrap_content"
  android:layout_height="wrap_content"
  android:gravity="center"  
  android:textSize="20sp"     
/>
</LinearLayout>

最佳答案

问题是,如果条件不满足,您不会重置文本颜色。在 ListView 中, View 被回收。

所以做这样的事情

if(s.length()==3) {
    holder.text.setTextColor(0xFF008B45); //green
}else{
    holder.text.setTextColor(xyz); //xyz
}

关于Android 自定义 ArrayAdapter 不停留在滚动条上,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17825370/

相关文章:

android - 软键盘隐藏了部分全屏 webview

安卓 :How to getText from Edittext in side ListView?

android ListView 滚动条样式

android - 在 Android Studio 中添加 Caldroid 库

Android 主题不适用于 Activity

java - 如何在整个应用程序上收听任何键盘?

java - 错误: Only the original thread that created a view hierarchy can touch its views on Android app

java - 将 Android 代码 fragment 从 Java 转换为 C# ("inline class extension")

android - SupportMapFragment 在 Android 4.1+ 上因 NullPointerException 而崩溃

android - ImageView:填充水平保持纵横比