好的,我想我有一个解决方案:
public class MyActivity extends Activity {
ListView listView;
ArrayAdapter<String> adapter;
int firstVisible;
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
listView = (ListView) findViewById(R.id.listView);
adapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1) {
@Override
public View getView(int position, View convertView, ViewGroup parent) {
View v = super.getView(position, convertView, parent);
processView(v, getItem(position), true);
return v;
}
};
for (int i = 0; i < 30; i++) {
adapter.add("Value " + String.valueOf(i + 1));
}
listView.setAdapter(adapter);
firstVisible = listView.getFirstVisiblePosition();
listView.setOnScrollListener(new AbsListView.OnScrollListener() {
@Override
public void onScrollStateChanged(AbsListView view, int scrollState) {
}
@Override
public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) {
if (firstVisibleItem != firstVisible) {
onFirstVisibleChanged(firstVisible, firstVisibleItem);
firstVisible = firstVisibleItem;
}
}
});
}
private void processView(View v, String value, boolean fromGetView) {
//if from get view we don't want to set yet wait till it comes from scrolling
if (value.contains("4") && !fromGetView) {
v.setBackgroundResource(android.R.color.holo_orange_light);
} else {
v.setBackgroundResource(android.R.color.transparent);
}
}
private void onFirstVisibleChanged(int oldIndex, int newIndex) {
View v = getViewForPosition(newIndex);
String val = adapter.getItem(newIndex);
processView(v, val, false);
}
/**
* @param position
* position of item in list
* @return null if position outside bounds
*/
public View getViewForPosition(int position) {
int firstPosition = listView.getFirstVisiblePosition() - listView.getHeaderViewsCount();
int wantedChild = position - firstPosition;
// Say, first visible position is 8, you want position 10, wantedChild will now be 2
// So that means your view is child #2 in the ViewGroup:
if (wantedChild < 0 || wantedChild >= listView.getChildCount()) {
return null;
}
return listView.getChildAt(wantedChild);
}
}
我解释该怎么做的最好方法就是自己尝试一下。
如果在滚动时字符串包含数字 4,我们会将背景颜色更改为橙色,这会创建一个字符串列表“Value n”最多 30。如果您希望删除视图,我们应该可以这样做:
private void processView(View v, String value, boolean fromGetView) {
//if from get view we don't want to set yet wait till it comes from scrolling
if (value.contains("4") && !fromGetView) {
adapter.remove(value);
} else {
//no action needed
}
}
但是,这可能会让用户感到非常困惑,因为当值 4 到达顶部时,它会被删除,而值 5 会取而代之。