以可扩展布局获取ImageView高度和宽度

时间:2018-02-23 07:25:35

标签: android android-imageview android-adapter

Altough我可以在onBindViewHolder中获得每个视图的宽度和高度,我无法在可扩展布局中获得imageView的宽度和高度。你知道为什么吗?

我的xml代码:

 <net.cachapa.expandablelayout.ExpandableLayout
                android:id="@+id/expandable_layout_0"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:layout_weight="1"
                android:visibility="visible"
                app:el_duration="0"
                app:el_expanded="true">

                <ImageView
                    android:id="@+id/imgActivityLineChart"
                    android:layout_width="match_parent"
                    android:layout_height="82dp"
                    android:layout_marginRight="10dp"
                    android:layout_marginStart="10dp"
                    android:background="@color/backgroundGray"
                    android:text="content"
                    app:layout_constraintBottom_toBottomOf="parent"
                    app:layout_constraintRight_toRightOf="parent"
                    app:layout_constraintStart_toStartOf="parent" />

            </net.cachapa.expandablelayout.ExpandableLayout>

我的java代码(在onBindViewHolder方法中):

    ((UserViewHolder) holder).btnExpand.setOnClickListener(new View.OnClickListener() {

public void onClick(View view) {

        imgwidth= userViewHolder.imgView.getWidth(); 
        imgheight= userViewHolder.imgView.getHeight();
        int test= userViewHolder.btnExpand.getHeight();

 }
        });

2 个答案:

答案 0 :(得分:0)

尝试下面的代码,使用observable来确保在阅读之前高度和宽度可用

((UserViewHolder) holder).btnExpand.setOnClickListener(new View.OnClickListener() {

        public void onClick(View view) {

          userViewHolder.imgView.getViewTreeObserver()
            .addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
                @Override
                public void onGlobalLayout() {
                    userViewHolder.imgView.getViewTreeObserver().removeOnGlobalLayoutListener(this);
                    width = userViewHolder.imgView.getWidth();
                    height = userViewHolder.imgView.getHeight();

                }
            });
        }
});

答案 1 :(得分:0)

yourView.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {

    @Override
    public void onGlobalLayout() {
        // Ensure you call it only once :
        yourView.getViewTreeObserver().removeGlobalOnLayoutListener(this);

        // Here you can get the size :)
    }
});

为我工作。