緣起:把前面寫的二篇合併起來,存到一個獨立類別檔,以便日後調用
Android 算法:遍歷巡覽ViewGroup找出所有子View[C# 替代Java的findViewsWithText方法]
Android 算法:遍歷巡覽ViewGroup找出所有子View[C# 以Xml方法3種實作] GetElementsByTagName、SelectNodes
呼叫端:
GameActivity.cs
void setNumBtnEnabled(bool setEnabled)
{
List<View> vList = new List<View>();
MyViewGroup myViewGroup = new MyViewGroup(this);
myViewGroup.FindViewsWithText(ref vList,
MyViewGroup.whatTraverseMethodToBeRun.withoutRecursion);
foreach (View item in vList)
{
item.Enabled = setEnabled;
}
}
被呼叫端:
MyViewGroup.cs
using Android.Content;
using Android.Views;
using Android.Util;
using System;
using System.Collections.Generic;
using System.Runtime.CompilerServices;
using Android.Widget;
using System.Xml;
using Android.Content.Res;
using Android.App;
namespace GuessGameAndroidPractise
{
public class MyViewGroup : ViewGroup
{
//Called from layout when this view should assign a size and position to each of its children.
//https://docs.microsoft.com/zh-tw/dotnet/api/android.views.viewgroup.onlayout?view=xamarin-android-sdk-9#Android_Views_ViewGroup_OnLayout_System_Boolean_System_Int32_System_Int32_System_Int32_System_Int32_
int _childCount = 0;
public new int ChildCount { get => _childCount; set => _childCount = value; }
Context _context1; static Activity activity;
public MyViewGroup(Context context) : base(context)
{
_context1 = context;
activity = (Activity)_context1;//https://stackoverflow.com/questions/9891360/getting-activity-from-context-in-android
}
protected override void OnLayout(bool changed, int l, int t, int r, int b)
{
//throw new System.NotImplementedException();
if (changed)
{
Left = l; Top = t;
Right = r; Bottom = b;
}
else
{
Left = l; Top = t;
Right = r; Bottom = b;
}
}
public enum whatTraverseMethodToBeRun
{
xml, recursion, withoutRecursion
}
//巡覽遍歷想要找的View,並取得List<View>,以便於對此群組作統一的操作
public void FindViewsWithText(//traverse_any_view_hierarchy_in_android
ref List<View> vList,whatTraverseMethodToBeRun method,
chooseAXmlMethodforTraverseViewGroup c
=

这篇博客将C#版的遍历ViewGroup并查找所有子View的算法整合到独立类中,提供了一种替代Java findViewsWithText的方法。内容包括呼叫端GameActivity.cs的调用示例和被呼叫端MyViewGroup.cs的详细实现,适用于Android开发者进行UI元素查找。
最低0.47元/天 解锁文章
1061

被折叠的 条评论
为什么被折叠?



