在Listview / View中获取第一项的可见高度

时间:2014-07-31 13:20:36

标签: android listview view header height

我需要在listivew中获得标题的可见高度。如何获得Listview(标题)或任何视图中第一项的高度。

我尝试了下面给出的方法但这些给了我原始高度的项目不可见的高度。

 view.getViewTreeObserver().addOnGlobalLayoutListener(new OnGlobalLayoutListener() {
 @SuppressLint("NewApi")
 @SuppressWarnings("deprecation")
 @Override
  public void onGlobalLayout() {
   //now we can retrieve the width and height
   int width = view.getWidth();
   int height = view.getHeight();
   //...
   //do whatever you want with them
   //...
   //this is an important step not to keep receiving callbacks:
   //we should remove this listener
   //I use the function to remove it based on the api level!

if(android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.JELLY_BEAN)
    view.getViewTreeObserver().removeOnGlobalLayoutListener(this);
   else
    view.getViewTreeObserver().removeGlobalOnLayoutListener(this);
  }
 });

view.measure(MeasureSpec.UNSPECIFIED, MeasureSpec.UNSPECIFIED);
int widht = view.getMeasuredWidth();
int height = view.getMeasuredHeight();

这也是

DisplayMetrics metrics = new DisplayMetrics();
      getWindowManager().getDefaultDisplay().getMetrics(metrics); height =
      metrics.heightPixels; width = metrics.widthPixels;

但没有得到任何结果。 提前致谢

1 个答案:

答案 0 :(得分:3)

你可以试试这个。让你的布局文件如下:

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/rl_container"
    android:layout_height="match_parent" 
    android:layout_width="match_parent">

    <ListView
        android:id="@+id/sample_list_view"
        android:layout_width="match_parent"
        android:layout_height="match_parent"/>
</RelativeLayout>

在您的活动java文件中:

ListView mListView = (ListView) findViewById(R.id.sample_list_view);
mListView.setAdapter(mAdapter);

// add header view.
// Let "mHeaderView" is a header view inflated from some layout file
mListView.addHeaderView(mHeaderView);

// let your listview's parent view (in layout file) is a relative layout
// with id = "rl_container" as shown in above XML layout file
RelativeLayout rlContainer = (RelativeLayout)findViewById(R.id.rl_container);

// To find visible height of the first item (header in this case)
// mListView.getChildAt(i) return view of the ith child from top.
// header is considered to be as 0th child.
// not sure about multiple headers. but it should be same.
View childView = mListView.getChildAt(0);

// visible height is bottom cordinate of the child view - top cordinate of the list view's parent container.
// here I am considering list view as the top child of its parent container.
// code can be modified accordingly to consider margins from top.
int visibleHeight = childView.getBottom() - rlContainer.getTop();
if(visibleHeight < 0) {
    //then item is not visible
}

当我在我的项目中使用它时,它对我有用。欢迎提出意见和建议。