Xamarin Android:循环活动中的所有控件



我有一个Android应用程序,每当用户单击图像(其中有几个(时,就会执行操作。 我想为每个图像集中设置一个侦听器,假设我们有 6 个。 而不是说

myImg0.Click += new MyImgClick;
myImg1.Click += new MyImgClick;

我希望有一种方法来运行foreach循环来快速设置点击事件侦听器, 类似的东西

foreach(img i in Application)
{
i.Click += new MyImgClick;
}

然后我可以使用事件处理程序,使用"sender"参数将允许我访问单击的单个图像。

我尝试阅读活动和捆绑类,但到目前为止还没有找到任何有价值的东西。 这似乎不是一种常见的方法,因为大多数搜索刚刚返回了"设置事件侦听器"的解决方案。

你可以遍历你的视图层次结构,并使用一个简单的递归方法获取你想要的所有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都将在这里作为输入,因此LinearLayoutRelativeLayout等。

如果您不提供根布局和 ID,则始终可以使用以下内容获取根目录:

var root = Window.DecorView.FindViewById<ViewGroup>(Android.Resource.Id.Content);

然后,您可以使用以下命令在此根上运行该方法,并使用以下方法获取所有ImageView

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>

这是否是最佳方法,我非常怀疑。也许你应该考虑一下使用RecyclerViewGridView或其他一些使用和Adapter提高内存效率的视图。这对您来说可能是一个更好的解决方案。

最新更新