ListView控件重用视图时......我不希望它我不、视图、控件、ListView

2023-09-11 11:58:29 作者:主席誇我長得帥

我有一个的ListView ,每个项目,其中包含了一个切换按钮。当我切换,然后向上或向下滚动,在ListView是回收的意见,所以其他一些人被镜像的切换按钮的选中状态。我不想这样。我怎样才能prevent呢?

I've got a ListView, each of item of which contains a ToggleButton. After I toggle it and then scroll up or down, the ListView is recycling the Views and so some of the others are mirroring the checked state of the ToggleButton. I don't want this. How can I prevent it?

推荐答案

Android的回收列表项性能的目的。强烈建议,如果你希望你的ListView顺利滚动重用他们。

Android recycles list items for performance purposes. It is highly recommended to reuse them if you want your ListView to scroll smoothly.

有关各列表项的适配器 getView 函数被调用。还有,就是你必须为ListView是要求该项目指定的值。

For each list item the getView function of your adapter is called. There, is where you have to assign the values for the item the ListView is asking for.

有一个看看这个例子:

@Override
public View getView(int position, View convertView, ViewGroup parent)
{
    ViewHolder holder = null;

    if ( convertView == null )
    {
        /* There is no view at this position, we create a new one. 
           In this case by inflating an xml layout */
        convertView = mInflater.inflate(R.layout.listview_item, null);  
        holder = new ViewHolder();
        holder.toggleOk = (ToggleButton) convertView.findViewById( R.id.togOk );
        convertView.setTag (holder);
    }
    else
    {
        /* We recycle a View that already exists */
        holder = (ViewHolder) convertView.getTag ();
    }

    // Once we have a reference to the View we are returning, we set its values.

    // Here is where you should set the ToggleButton value for this item!!!

    holder.toggleOk.setChecked( mToggles.get( position ) );

    return convertView;
}

注意 ViewHolder 是我们用回收的观点静态类。它的属性是您的列表项目有意见。它是在你的适配器声明。

Notice that ViewHolder is a static class we use to recycle that view. Its properties are the views your list item has. It is declared in your adapter.

static class ViewHolder{
    ToggleButton toggleOk;
}

mToggles 被声明为在您的适配器的私人财产,设置这样一个公共方法:

mToggles is declared as a private property in your adapter and set with a public method like this:

public void setToggleList( ArrayList<Boolean> list ){
        this.mToggles = list;
        notifyDataSetChanged();
    }

有一个在其他自定义的ListView示例以获取更多信息。

Have a look at other custom ListView examples for more information.

希望它帮助。