LoginSignup
0
0

More than 5 years have passed since last update.

Xamarin.Android の複数の View を一括処理したい

Posted at

発端

  • Xamarin.Android で
  • 複数の View を非表示にしたい
  • HTML の class のようなもので一括処理したい
  • android:tag が使えるのでは

View ツリーを再帰的に検索する

  • ViewGroup.ChildCount
  • ViewGroup.GetChildAt(index)
  • 検索の起点はたぶん Window.DecorView
  • 再帰の書き方はお好みで

再帰関数から IEnumerable<View> をもらう例

private IEnumerable<View> EnumlateChildViews(View view)
{
    if (view is ViewGroup viewGroup)
    {
        for (int i = 0; i < viewGroup.ChildCount; ++i)
        {
            foreach (var result in EnumlateChildViews(viewGroup.GetChildAt(i)))
            {
                yield return result;
            }
        }
    }
    else
    {
        yield return view;
    }
}
foreach (var hoge in EnumlateChildViews(this.Window.DecorView).Where(_ => _.Tag?.ToString() == "hoge"))
{
    hoge.Visibility = ViewStates.Invisible;
}

再帰関数に Action<View> を渡す例

private void ForEachChildViews(View view, Action<View> action)
{
    if (view is ViewGroup viewGroup)
    {
        for (int i = 0; i < viewGroup.ChildCount; ++i)
        {
            ForEachChildViews(viewGroup.GetChildAt(i), action);
        }
    }
    else
    {
        action(view);
    }
}
ForEachChildViews(this.Window.DecorView, view =>
{
    if (view.Tag?.ToString() == "hoge")
    {
        view.Visibility = ViewStates.Invisible;
    }
});
0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0