【问题标题】:Android ListView scrollToAndroid ListView 滚动到
【发布时间】:2010-11-24 15:52:00
【问题描述】:

我有一个LinearLayout,其中包含一些其他视图,其中还有一个ListView。 此视图是通过单击按钮从另一个视图加载的。

此按钮以某种方式指定 ListView 中的哪个元素需要成为列表中的第一个可见元素。填充列表的元素是通过 HTTP 从外部服务器检索的。

问题是我可以让第 N 个元素成为列表中的第一个。 请注意,我不想将它从当前位置移动到新位置,我希望列表滚动。

我尝试过使用setSelected()scrollTo(x,y)scrollBy(x,y),但没有成功。

我也尝试了这段代码,尽管它很丑,但我只是想试试它是否有效:

ListView categoryList = (ListView)findViewById(R.id.category_list);
        categoryList.post(new Runnable() {
            @Override
            public void run() {
                Log.d(this.getClass().getName(), "CategoryActivity.scrollToIndex: " + CategoryActivity.scrollToIndex);
                if(CategoryActivity.scrollToIndex>0){
                    ListView categoryList = (ListView)findViewById(R.id.category_list);
                    categoryList.setScrollContainer(true);
                    categoryList.scrollTo(4, CategoryActivity.scrollToIndex * 50);
                    categoryList.requestLayout();

                }
            }
        });

这给了我一些成功,但是 ListView 当时的行为疯狂,我什至无法描述......

有什么想法吗?

【问题讨论】:

    标签: android android-listview android-scroll


    【解决方案1】:

    尝试将其添加到消息队列中

    categoryList.post(new Runnable() {
        public void run() {
            categoryList.scrollTo(4, CategoryActivity.scrollToIndex * 50);
        }
    });
    

    它在 ScrollView (check this answer) 中对我有用。

    【讨论】:

    • 我也尝试过 setSelected 并且它也有效。所以,我找到了解决我的问题的方法!我还没有清楚地理解为什么会这样:/
    【解决方案2】:

    我制作的函数可能对其他人有用的列表视图滚动,它们适用于每个 android 版本、模拟器和设备,这里 itemheight 是列表视图中视图的固定高度。

    int itemheight=60;
    public void scrollToY(int position)
    {
        int item=(int)Math.floor(position/itemheight);
        int scroll=(int) ((item*itemheight)-position);
        this.setSelectionFromTop(item, scroll);// Important
    }
    public void scrollByY(int position)
    {
        position+=getListScrollY();
        int item=(int)Math.floor(position/itemheight);
        int scroll=(int) ((item*itemheight)-position);
        this.setSelectionFromTop(item, scroll);// Important
    }
    public int getListScrollY()
    {
        try{
        //int tempscroll=this.getFirstVisiblePosition()*itemheight;// Important
        View v=this.getChildAt(0);
        int tempscroll=(this.getFirstVisiblePosition()*itemheight)-v.getTop();// Important
        return tempscroll;
        }catch(Exception e){}
        return 0;
    }
    

    【讨论】:

      猜你喜欢
      • 2018-02-27
      • 2011-02-22
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-05-17
      • 1970-01-01
      • 2014-10-17
      • 2014-03-02
      相关资源
      最近更新 更多