可以遍歷您的視圖層次,並得到所有你想要的ImageViews用這樣一個簡單的遞歸方法:
private IEnumerable<T> GetViewsByType<T>(ViewGroup root) where T : View
{
var children = root.ChildCount;
var views = new List<T>();
for (var i = 0; i < children; i++)
{
var child = root.GetChildAt(i);
if (child is T myChild)
views.Add(myChild);
else if (child is ViewGroup viewGroup)
views.AddRange(GetViewsByType<T>(viewGroup));
}
return views;
}
任何ViewGroup
類型的View
將作爲輸入這裏工作,所以LinearLayout
,RelativeLayout
等
如果你不給你的根佈局和ID你總是可以得到根用:
var root = Window.DecorView.FindViewById<ViewGroup>(Android.Resource.Id.Content);
然後你可以運行在這根與方法,並得到所有ImageView
S:
var imageViews = GetViewsByType<ImageView>(root);
我已經在此佈局測試這一點,它發現所有的ImageView
很好,沒有問題:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent">
<LinearLayout
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent">
<ImageView
android:layout_width="wrap_content"
android:layout_height="wrap_content"/>
<ImageView
android:layout_width="wrap_content"
android:layout_height="wrap_content"/>
<ImageView
android:layout_width="wrap_content"
android:layout_height="wrap_content"/>
<LinearLayout
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent">
<ImageView
android:layout_width="wrap_content"
android:layout_height="wrap_content"/>
<LinearLayout
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent">
<ImageView
android:layout_width="wrap_content"
android:layout_height="wrap_content"/>
<ImageView
android:layout_width="wrap_content"
android:layout_height="wrap_content"/>
</LinearLayout>
</LinearLayout>
</LinearLayout>
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="match_parent">
<ImageView
android:layout_width="wrap_content"
android:layout_height="wrap_content"/>
</RelativeLayout>
<FrameLayout
android:layout_width="match_parent"
android:layout_height="match_parent">
<ImageView
android:layout_width="wrap_content"
android:layout_height="wrap_content"/>
<ImageView
android:layout_width="wrap_content"
android:layout_height="wrap_content"/>
<ImageView
android:layout_width="wrap_content"
android:layout_height="wrap_content"/>
</FrameLayout>
</LinearLayout>
無論是做這件事的最佳方式,我都非常懷疑它。也許你應該考慮一些關於使用RecyclerView
,GridView
或其他一些使用和Adapter
更高的內存效率的觀點。這對你來說可能是更好的解決方案。