listView 中的相关positon 的使用和注意的地方

listView 这个空间中有很多关于位置变化的方法,

写了一个demo代码如下:

 

public class MainActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        final ListView listView = (ListView) findViewById(R.id.listView);
        String arr[] = new String[]{"猴子", "猴子", "猴子", "猴子", "猴子", "猴子", "猴子"};
        listView.setAdapter(new ArrayAdapter<>(this, R.layout.adapter_layout, arr));
        final int firstSeePostion = listView.getFirstVisiblePosition();
    listView.getLastVisiblePosition()
        listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                final int lastSeePostion =   firstSeePostion + listView.getChildCount()  ;
                Toast.makeText(MainActivity.this, "你点击的位置是 " + position + "+" + firstSeePostion + "+" + listView.getHeight() + "+" + listView.getChildAt(position).getBottom() + "+" + listView.getChildCount() + "+" + lastSeePostion, Toast.LENGTH_SHORT).show();
            }
        });


    }

点击不同的item 弹出的值:

其中:firstSeePostion 是在屏幕上显示的第一个位置,一般值为0。

listView.getHeight 是指listView 这个控件的高度,

listView.getChildCount 是在ViewGroup 中的子View的个数,也就mChildren[] 中的count,其实这个count 值的大小应该是我们屏幕上能看见的数量,我们比如在屏幕上能看见4个listView 的item,那么listView.getChildCount 的值就是 4 ,listView.getChildAt(position),这个方法中的position 的值的范围在 position > 0 && postion < count lastSeePostion 这个值 mFirstPosition + getChildCount() - 1; 注意这个值的获取,需要在子线程中获取,因为getChildCount 这个值是 直接获取不到的,需要绘制后,才能获取到,所以在用的时候 通过以下的方式获取:




private class ScrollListRunnable implements Runnable {

    private int mPosition;

    public ScrollListRunnable(int position) {
        mPosition = position;
    }

    @Override
    public void run() {
        int firstVisiblePosition = mOrderQuestionListView.getFirstVisiblePosition();
        int lastVisiblePosition = mOrderQuestionListView.getLastVisiblePosition();
        if (mPosition >= firstVisiblePosition && mPosition <= lastVisiblePosition) {
            int childIndex = mPosition - firstVisiblePosition;
            View child = mOrderQuestionListView.getChildAt(childIndex);
            int childBottom = child.getBottom();
            int listHeight = mOrderQuestionListView.getHeight();
            if (childBottom > listHeight) {
                int newChildTop = listHeight - child.getHeight();
                mOrderQuestionListView.smoothScrollToPositionFromTop(mPosition, newChildTop);
            }

        }
    }
}


 


 类似这段代码中的方式去实现。


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值