簡體   English   中英

在可擴展布局中獲取ImageView的高度和寬度

[英]Get ImageView height and width in expandable layout

盡管可以在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();

 }
        });

嘗試下面的代碼,它是可觀察的,以確保在讀取高度和寬度之前可用

((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();

                }
            });
        }
});
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 :)
    }
});

為我工作。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM