使用 FindViewById <> 在尝试获取 BottomNavigationView 时返回 null



我的GradientTabbedPage有一个自定义渲染器,我正试图为BottomNavigationView设置渐变背景,但我尝试使用的每个资源Id都返回null。

public class GradientTabbedPageRenderer : TabbedPageRenderer
{
public GradientTabbedPageRenderer(Context context) : base(context) { }
protected override void OnElementChanged(ElementChangedEventArgs<TabbedPage> e)
{
base.OnElementChanged(e);
var control = (GradientTabbedPage)Element;
var tabs = FindViewById<BottomNavigationView>(Resource.Id.bottomtab_tabbar);
if (tabs == null) return;
tabs.SetBackground(new GradientDrawable(GradientDrawable.Orientation.LeftRight,
new int[] { control.TopColor.ToAndroid(), control.BottomColor.ToAndroid() }));
}
}

我已经尝试了以下资源。Ids:

bottomtab_tabbar
bottomtab_navarea
bottom
main_tablayout

我不明白为什么安卓系统要像iOS那样难以暴露不同的元素。我是渲染器的新手,但据我所见,iOS做得更好。

这可以帮助您

protected override void OnElementChanged(ElementChangedEventArgs<TabbedPage> e)
{
base.OnElementChanged(e);
var control = (GradientTabbedPage)Element;
var gradientDrawable = new GradientDrawable(GradientDrawable.Orientation.LeftRight,
new int[] { control.TopColor.ToAndroid(), control.BottomColor.ToAndroid() });
var relativeLayout = this.GetChildAt(0) as Android.Widget.RelativeLayout;
var bottomNavigationView = relativeLayout.GetChildAt(1) as BottomNavigationView;
bottomNavigationView.SetBackground(gradientDrawable);
bottomNavigationView.Elevation = 0;
}

我所看到的问题是您没有使用正确的Context。

首先需要理解的是,每一项活动都将布局设置为内容视图,并有其生命周期。

我想您在某个活动中的某个地方使用了这个类GradientTabbedPageRenderer(我在这里将其命名为YourHolderActivity(。要了解其元素,您需要提供其上下文或活动本身。

如何修复:

  1. 在类的构造函数中传递活动
  2. 按活动上下文查找视图

public class GradientTabbedPageRenderer : TabbedPageRenderer
{
public YourHolderActivity _yourHolderActivity;

public GradientTabbedPageRenderer(YourHolderActivity yourHolderActivity, Context context) : base(context) 
{
_yourHolderActivity = yourHolderActivity;
}
protected override void OnElementChanged(ElementChangedEventArgs<TabbedPage> e)
{
base.OnElementChanged(e);
var control = (GradientTabbedPage)Element;
var tabs = _yourHolderActivity.FindViewById<BottomNavigationView>(Resource.Id.bottomtab_tabbar);
if (tabs == null) return;
tabs.SetBackground(new GradientDrawable(GradientDrawable.Orientation.LeftRight,
new int[] { control.TopColor.ToAndroid(), control.BottomColor.ToAndroid() }));
}
}

最新更新