ListView 获取精确滚动值

ListView 获取精确滚动值

@[Android|listview|滚动]
场景

当我们要求listview一往上滚动的时候,下面的tab栏或者别的在下面浮空的东西,或者上面的ActionBar也是可以要求往上滚动(例如google plus),这个时候我们需要精确的ListView 滚动值,而不某个Item往上滚动了,毕竟是用了卡片设计后会出现一行会很高的情况,这时候过了一个在往下滑动明显就不合适了

获取的方法很简单看代码

package org.hangox.test;

import android.os.Bundle;
import android.support.v7.app.ActionBarActivity;
import android.view.View;
import android.widget.AbsListView;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.TextView;

import com.lidroid.xutils.util.LogUtils;

import java.util.ArrayList;

import butterknife.ButterKnife;
import butterknife.InjectView;

/**
 * Created With Android Studio
 * User 47
 * Date 2014-10-28
 * Time 23:27
 */
public class ListViewScrollTest extends ActionBarActivity{
    @InjectView(R.id.listView)
    ListView listView;
    View headView ;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_list_scroll);
        ButterKnife.inject(this);
        ArrayList<String> stringArrayList = new ArrayList<String>();
        for(int i = 0 ;i < 10000; i ++){
            stringArrayList.add(i+"");
        }
        listView.setAdapter(new ArrayAdapter<String>(this,android.R.layout.simple_list_item_1, stringArrayList));
        headView = new TextView(this);
//        listView.addHeaderView(headView);
        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) {
                LogUtils.i(getScrollY()+"");
            }
        });
    }

    public int getScrollY() {//获取滚动距离
        View c = listView.getChildAt(0);
        if (c == null) {
            return 0;
        }

        int firstVisiblePosition = listView.getFirstVisiblePosition();
        int top = c.getTop();

        int headerHeight = 0;
        if (firstVisiblePosition >= 1) {
            headerHeight = listView.getHeight();
        }
        return -top + firstVisiblePosition * c.getHeight() + headerHeight;
    }
}

不要问我为什么,只是知道这样可以获取到滚动距离,但是具体原因还没有分析

    原文作者:@47
    原文地址: https://www.cnblogs.com/Jabba93/p/4059497.html
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞