Skip to content

Instantly share code, notes, and snippets.

@nodoid
Created April 1, 2019 23:39
Show Gist options
  • Save nodoid/67e510b74eb2037b444ba3bfd206f2f5 to your computer and use it in GitHub Desktop.
Save nodoid/67e510b74eb2037b444ba3bfd206f2f5 to your computer and use it in GitHub Desktop.
Iterate views
public class IterateView
{
readonly StringBuilder sb = new StringBuilder();
const string PADDING_STRING = " ";
string sPadding = "";
public string OutputString { get; private set; }
public int NumberOfType { get; private set; }
public List<string> GetText { get; private set; }
public void Iterate(View view)
{
GetText = new List<string>();
if (view is ViewGroup)
IterateViewChildren(view);
else
sb.AppendLine(sPadding + view.GetType().Name);
OutputString = sb.ToString();
}
void IterateViewChildren(View view)
{
if (view is ViewGroup)
{
sb.AppendLine(sPadding + view.GetType().Name + " (ViewGroup)");
sPadding += PADDING_STRING;
ViewGroup vGroup = (ViewGroup)view;
for (int i = 0; i < vGroup.ChildCount; i++)
{
if (!(vGroup.GetChildAt(i) is ViewGroup))
sb.AppendLine(sPadding + vGroup.GetChildAt(i).GetType().Name);
View vChild = vGroup.GetChildAt(i);
IterateViewChildren(vChild);
}
// Remove padding after iterating children to get us back to where we need to be
sPadding = sPadding.Remove(sPadding.Length - PADDING_STRING.Length);
}
}
public void GetChildrenInLayout<T>(LinearLayout view)
{
if (view != null)
{
var ll = view.ChildCount;
for(var i = 0; i < ll; ++i)
{
var v = view.GetChildAt(i);
if (v is T)
{
NumberOfType++;
}
if (v is LinearLayout l)
{
GetChildrenInLayout<T>(l);
}
}
}
}
public void GetChildrenTextInLayout<T>(LinearLayout view, T widget)
{
Type wid = widget.GetType();
if (view != null)
{
var ll = view.ChildCount;
for (var i = 0; i < ll; ++i)
{
var v = view.GetChildAt(i);
if (v is T)
{
var et = Convert.ChangeType(v, wid);
var args = et.GetType().GetProperty("Text").GetValue(et, null);
GetText.Add(args.ToString());
}
if (v is LinearLayout l)
{
GetChildrenTextInLayout(l, widget);
}
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment