关于改变ListView选中项的状态方法

关于改变ListView选中项的状态方法

思路:无论使用哪一个适配器,只需要重写他的getView()方法即可

原理:getView方法是用于把创建好的view交给listView用的,所以我们可以对创建好的view进行一个修改再交给ListView

例子:

    public class MyListView extends ListView implements OnItemClickListener{
    <span class="pl-c">//用于记录点到了哪一个</span>
    <span class="pl-k">private</span> <span class="pl-k">int</span> mSelectPositon

    <span class="pl-k">public</span> MyListView(<span class="pl-smi">Context</span> context, <span class="pl-smi">AttributeSet</span> attr){
        <span class="pl-v">super</span>(context,attr);
        <span class="pl-v">this</span><span class="pl-k">.</span>setOnItemClickListener(<span class="pl-v">this</span>)
    }

    @<span class="pl-smi">Override</span>
    <span class="pl-k">public</span> <span class="pl-k">void</span> onItemClick(<span class="pl-k">AdapterView&lt;?&gt;</span> parent, <span class="pl-smi">View</span> view, <span class="pl-k">int</span> position, <span class="pl-k">long</span> id){
        <span class="pl-v">this</span><span class="pl-k">.</span>mSelectPosition <span class="pl-k">=</span> position;
    }

    <span class="pl-k">class</span> <span class="pl-en">adapter</span> <span class="pl-k">extends</span> <span class="pl-e">ArrayAdapter</span>{

        <span class="pl-k">@Override</span>
        <span class="pl-k">public</span> <span class="pl-smi">View</span> <span class="pl-en">getView</span>(<span class="pl-k">int</span> <span class="pl-v">position</span>, <span class="pl-smi">View</span> <span class="pl-v">convertView</span>, <span class="pl-smi">ViewGroup</span> <span class="pl-v">parent</span>) {

                <span class="pl-smi">TextView</span> view <span class="pl-k">=</span>  (<span class="pl-smi">TextView</span>)<span class="pl-v">super</span><span class="pl-k">.</span>getView(position, convertView, parent);
                <span class="pl-k">if</span>(position <span class="pl-k">==</span> mSelectPosition){                
                    view<span class="pl-k">.</span>textColor(<span class="pl-smi">Color</span><span class="pl-c1"><span class="pl-k">.</span>WHITE</span>);
                }<span class="pl-k">else</span>{
                    view<span class="pl-k">.</span>textColor(<span class="pl-smi">Color</span><span class="pl-c1"><span class="pl-k">.</span>BLACK</span>);                
                }
                <span class="pl-k">return</span> view;
        }   
    }
}

posted @ 2015-03-28 13:42  cirno_9  阅读(413)  评论(0编辑  收藏  举报