我正在使用 V4.Fragments。所以从 Activity 中我正在创建我的 fragment 的新实例,然后我开始交易。
主要问题是我的 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;
}
诡计没有奏效。始终返回零(高度/宽度)。
第二种,我直接在MyFragment
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 对不起我的工程师。
最佳答案
一切正常,我做错了什么。
所以这段代码效果很好:
imgView.ViewTreeObserver.GlobalLayout += (sender, e) =>
{
ImgHeight = imgView.Height;
ImgWidth = imgView.Width;
};
尽情享受吧!
关于android - 从 Android.Support.V4.Fragment 获取 imageView 的高度/宽度(始终返回零),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33415509/