在onMeasure中获取子视图大小

时间:2017-01-03 12:20:29

标签: android android-layout

我有listView,其中的项目是dynamicaly.Each项目是我的自定义视图,包含(从上到下)header,imageView和footer.I在onMeasure方法中设置项目的高度。我喜欢imageView的高度恰好是

 image_height=item_height-(footer_height+header_height)

我在xml中设置页脚/标题高度(常量值) 但是,当我尝试获取页脚/标题高度时,它返回0

@Override
public void onMeasure(int widthSpec, int heightSpec) {
    super.onMeasure(widthSpec,heightSpec);
    int widthMode = MeasureSpec.getMode(widthSpec);
    int widthSize = MeasureSpec.getSize(widthSpec);
    int heightMode = MeasureSpec.getMode(heightSpec);
    int heightSize = MeasureSpec.getSize(heightSpec);
    //float ar=896f/768f;
    int itemWidth=widthSize/IMGS_PER_ROW;
    int calculated_width =widthSize;
    int calculated_height = (int) (itemWidth*(1/IMG_ASPECT_RATIO));
    if(!initialized) {
        Image img=new Image(this.getContext());
        int dy=((ImageView)this.findViewById(R.id.separator)).getHeight();//returns 0
        Log.d("item",calculated_width+","+calculated_height+","+dy);
        initialized=true;
    }
    this.setMeasuredDimension(calculated_width, calculated_height);
}

项目布局:

<?xml version="1.0" encoding="utf-8"?>
<com.rhyboo.net.listtest.ListItemView xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent" android:layout_height="match_parent"
android:orientation="vertical">

<TextView
    android:text="Title"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:id="@+id/title_text"
    android:gravity="left"
    android:textSize="24sp" />
<LinearLayout
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="horizontal"
    android:id="@+id/items_container"
    android:layout_marginBottom="30dp"
    android:layout_marginTop="30dp">
</LinearLayout>
<ImageView
    android:layout_width="match_parent"
    android:layout_height="30dp"
    app:srcCompat="@color/colorAccent"
    android:id="@+id/separator"
    android:layout_gravity="bottom" />
 </com.rhyboo.net.listtest.ListItemView>

0 个答案:

没有答案