【问题标题】:Xamarin Forms - Changing ImageView from Android Toolbar.axml dynamicallyXamarin Forms - 从 Android Toolbar.axml 动态更改 ImageView
【发布时间】:2018-08-14 22:18:15
【问题描述】:

要在 Xamarin Forms 应用的导航栏中实现徽标(适用于 Android 案例),我使用以下 Toolbar.axml 文件:

<?xml version="1.0" encoding="utf-8"?>
<android.support.v7.widget.Toolbar 
xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/toolbar"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="?attr/colorPrimary"
android:theme="@style/ThemeOverlay.AppCompat.Dark.ActionBar"
android:popupTheme="@style/ThemeOverlay.AppCompat.Light">

<RelativeLayout android:layout_width="wrap_content"
        android:layout_height="fill_parent">

<ImageView
android:id="@+id/logo"
        android:layout_width="wrap_content"
        android:layout_height="fill_parent"
        android:scaleType="fitCenter"
        android:src="@drawable/xlogo_small" 
        android:layout_gravity="right"
        android:layout_alignParentRight="true" />
</RelativeLayout>
</android.support.v7.widget.Toolbar>

但现在我想根据应用程序加载后由 Web 服务调用确定的 boolean 值动态更改 xlogo_small.png。我宁愿访问toolbar.axml 以从Xamarin Forms Shared Project 动态编辑徽标,因为所有逻辑都位于其中。但是,我也没有在 Xamarin.Android 项目中找到一种方法。 Xamarin Forms / Android 案例的任何解决方案?

【问题讨论】:

  • 在android项目中调用一个方法的简单依赖服务怎么样?它只会获取应用程序的当前工具栏,然后更改图像视图的 src 属性。
  • 这是第一个想到的,但如果不是来自 MainActivity.cs,FindViewById 方法似乎不可用。我希望在直接从 Xamarin Forms 或通过依赖服务找到工具栏方面获得一些帮助

标签: android xamarin.forms xamarin.android


【解决方案1】:

如何应用工具栏?我不确定它是如何完成的,但我知道如何获得默认值。

在您的 android 项目中创建 NavigationPageRenderer。

在“OnAttachedToWindow”覆盖中调用此方法

private void GetToolbar()
{
    Android.Support.V7.Widget.Toolbar toolbar = null;

    for (int i = 0; i < ChildCount; i++)
    {
        var child = GetChildAt(i);
        toolbar = child as Android.Support.V7.Widget.Toolbar;
        if (toolbar != null)
        {
            //Here toolbar is found.
            //You might loop through the toolbars children and find your ImageView
            break;
        }
    }
}

【讨论】:

  • 如何获得 ChildCount?
  • toolbar.ChildCount :P(你可以像我在“GetToolbar”方法中那样做
  • 您的第一个循环是否是指遍历一组子项,其中一个是我们想要的工具栏?在这种情况下,在 if 条件内,我需要另一个循环来遍历 toolbar.ChildCount?如果是这样,第一个循环中的 ChildCount 指的是什么?
  • 是的,我的意思是这个。第一个 childcount 指的是 NavigationPageRenderer,或者更具体地是指它从层次结构中更高位置继承的“ViewGroup”。 (在我的回答中提到)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-02-17
  • 2013-04-12
  • 2020-11-05
相关资源
最近更新 更多