使用数据绑定

时间:2018-05-29 11:11:29

标签: java android xml android-layout android-databinding

我的xml中有一个ImageView,它使用数据绑定库,其高度为" match_parent" ,现在我需要在运行时更改其高度,但是当我得到它的宽度时,它总是给我0,如何获得它的实际宽度尺寸?

我在xml中的ImageView下面有这个:

<ImageView
    android:layout_width="match_parent"
    android:layout_height="200dp"
    android:scaleType="centerCrop"
    app:imageUrl="@{data.bannerImage}"
    tools:src="@drawable/iop"
    android:src="@drawable/iop"/>

我正在使用以下java代码

将其高度设置为宽度比
@Override
public void onResume() {
   super.onResume();

   mBinding.notifyChange();
   mBinding.bannerImage.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
       @Override
       public void onGlobalLayout() {
           ViewGroup.LayoutParams params = mBinding.bannerImage.getLayoutParams();
           Log.e("tag","mBinding.bannerImage.getWidth()=="+mBinding.tvReviews.getWidth());
           params.height= (int)(mBinding.tvReviews.getWidth()/1.75);
           mBinding.bannerImage.setLayoutParams(params);
           Log.e("tag,"params.height=="+params.height);
           mBinding.bannerImage.getViewTreeObserver().removeOnGlobalLayoutListener(this);
           mBinding.notifyPropertyChanged(com.webkul.mobikulmp.BR.bannerImage);
       }
   });
}

这里 mBinding = DataBindingUtil.setContentView(this,R.layout.activity_seller_profile);,//在这里替换你的xml,但我总是为mBinding.bannerImage.getWidth()返回0。我也试过给ImageView提供修复宽度,并且在一些按钮点击监听器上获得它的宽度,但都是徒劳的。

感谢任何帮助

2 个答案:

答案 0 :(得分:0)

您可以使用以下代码在运行时获取View的宽度和高度

 int Height, Width;
    final ImageView imgview = (ImageView)findViewById(R.id.scaled_image);
    ViewTreeObserver vto = imgview .getViewTreeObserver();
    vto.addOnPreDrawListener(new ViewTreeObserver.OnPreDrawListener() {
        public boolean onPreDraw() {
            imgview .getViewTreeObserver().removeOnPreDrawListener(this);
            Height = imgview .getMeasuredHeight();
            Width = imgview .getMeasuredWidth();
            tv.setText("Height: " + Height + " Width: " + Width);
            return true;
        }
    });

答案 1 :(得分:0)

bcoz你为ImageView添加ViewTreeObserver并获得&#34; tvReviews&#34;的宽度TextView中。所以改变代码如下

mBinding.bannerImage.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
        @Override
        public void onGlobalLayout() {
            ViewGroup.LayoutParams params = mBinding.bannerImage.getLayoutParams();
            Log.e("tag","mBinding.bannerImage.getWidth()=="+mBinding.bannerImage.getWidth());
            params.height= (int)(mBinding.bannerImage.getWidth()/1.75);
            mBinding.bannerImage.setLayoutParams(params);
            Log.e("tag,"params.height=="+params.height);
                    mBinding.bannerImage.getViewTreeObserver().removeOnGlobalLayoutListener(this);
            mBinding.notifyPropertyChanged(com.webkul.mobikulmp.BR.bannerImage);
        }
    });