我正在使用V4。片段。因此,从活动中我创建了我的片段的新实例,然后开始交易
主要问题是我的imageview控件被定义为(在axml中)为Layout_width="match_parent"
和weightSum=1
(高度)
出于某种原因,我需要知道我的imageView的 高度 / 宽度 。
我尝试了什么:
是创建实现 IOnGlobalLayoutListener
class GlobalLayoutListener : Java.Lang.Object, ViewTreeObserver.IOnGlobalLayoutListener
{
System.Action _OnGlobalLayout;
public GlobalLayoutListener (System.Action onGlobalLayout)
{
this._OnGlobalLayout = onGlobalLayout;
}
public void OnGlobalLayout ()
{
_OnGlobalLayout ();
}
}
之后,在我的V4.Fragment课程中,我这样做:
public override View OnCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)
{
Arguments = new Bundle();
View _View = inflater.Inflate(Resource.Layout.MyFragmentLayout, container, false);
imgView = _View.FindViewById<ImageView>(Resource.Id.imgView);
Action CallBack = () =>
{
ImgHeight = imgView.Height;
ImgWidth = imgView.Width;
};
//new instance of class,that implements IOnGlobalLayoutListener
GlobalLayoutListener Global = new GlobalLayoutListener(CallBack);
imgView.ViewTreeObserver.AddOnGlobalLayoutListener(Global);
retun _View;
}
Trick没有奏效。始终返回零(高度/宽度) 第二个变体,我直接在 MyFragment
中实现了 IOnGlobalLayoutListener 的界面 public class MyCustomFragment : Android.Support.V4.App.Fragment,View.IOnTouchListener,ViewTreeObserver.IOnGlobalLayoutListener
{
int ImgHeight;
int ImgWidth;
ImageView imgView;
Bundle Arguments;
public override View OnCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)
{
Arguments = new Bundle();
View _View = inflater.Inflate(Resource.Layout.MyFragmentLayout, container, false);
imgView = _View.FindViewById<ImageView>(Resource.Id.imgView);
ViewTreeObserver Vto = imgView.ViewTreeObserver; //also tried with _View.ViewTreeObserver; result same
Vto.AddOnGlobalLayoutListener(this);
retun _View;
}
同样的问题,没有用。
我的最后一个变体就像:
public class MyCustomFragment : Android.Support.V4.App.Fragment
{
int ImgHeight;
int ImgWidth;
ImageView imgView;
Bundle Arguments;
public override View OnCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)
{
Arguments = new Bundle();
View _View = inflater.Inflate(Resource.Layout.MyFragmentLayout, container, false);
imgView = _View.FindViewById<ImageView>(Resource.Id.imgView);
imgView.ViewTreeObserver.GlobalLayout += (sender, e) => //also tried with _View
{
ImgHeight = imgView.Height;
ImgWidth = imgView.Width;
};
retun _View;
}
再次没有运气,我做错了什么?感谢。
PS抱歉我的英文。
答案 0 :(得分:1)
一切正常,我做错了。
所以这段代码很有用:
imgView.ViewTreeObserver.GlobalLayout += (sender, e) =>
{
ImgHeight = imgView.Height;
ImgWidth = imgView.Width;
};
享受!