简体   繁体   English

如何将选定的项目推到列表视图android的顶部

[英]how to push selected item to top in listview android

I have around 5 views in my listview and I want to push the selected view to top of the listview(set the position 0) and move down rest of the views. 我的列表视图中大约有5个视图,我想将选定的视图推到列表视图的顶部(将位置设置为0),然后将其余视图向下移动。 For example my views go like this from top to bottom 例如我的观点从上到下都是这样

1-2-3-4-5 1-2-3-4-5

when I select the third one then I want the listview be like this: 当我选择第三个时,我希望listview是这样的:

3-1-2-4-5 but of course their last position id must be in order such 1-2-3-4-5 3-1-2-4-5,但当然,其最后一个位置ID必须顺序为1-2-3-4-5

I made you a small example how you can reorder your list, please note that this only works for buttons ( you can just change the cast to a View if you are moving entire views. Also, this only works on one button for now, but you can change that easily! 我为您提供了一个小示例,说明如何重新排序列表,请注意,这仅适用于按钮(如果要移动整个视图,则只能将演员表更改为视图。此外,此操作目前仅适用于一个按钮,但是您可以轻松更改它!

Button btn = (Button)findViewById(R.id.button1);
btn.setOnClickListener(new OnClickListener() {
    @Override
    public void onClick(View arg0) {
        // create a new list
        ArrayList<Button> list = new ArrayList<Button>();
        ScrollView view = (ScrollView)findViewById(R.id.scrollView1);

        // add your clicked element on position 0
        list.add ( (Button) arg0 );

        for ( int i = 0; i < view.getChildCount(); i++ ) {
            if ( view.getChildAt(i) != arg0 ) {
                list.add( (Button) view.getChildAt(i));
            }
        }

        view.removeAllViews();

        for ( int x = 0; x < list.size(); x++ ) {
            view.addView(list.get(x));
            list.remove(x);
        }
    }
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM