首页 > 解决方案 > ImageCell 仅在 Android 上不显示图像

问题描述

一段时间以来,我一直在尝试使用共享库让 ImageCell 在非常基本的 ListView 中显示图像。该问题仅出现在 Android 上,iOS 版本按预期工作。

PS:我也遇到了从互联网加载图像的问题,同样仅适用于 Android。我确定问题是一样的。我已经在清单中添加了 Internet 权限,并尝试了所有不同的 HttpClientImplementation 和 SSL/TLS 实现选项。

我的 XAML 如下:

<?xml version="1.0" encoding="UTF-8"?>
<ContentPage
    xmlns="http://xamarin.com/schemas/2014/forms"
    xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
    x:Class="TestXamarin.GreetPage">
    <ListView x:Name="listView">
        <ListView.ItemTemplate>
            <DataTemplate>
                <ImageCell Text="{Binding Name}" Detail="{Binding Status}" ImageSource="{Binding ImageUrl}" />
            </DataTemplate>
        </ListView.ItemTemplate>
    </ListView>
        
</ContentPage>

类后面的代码是这样的:

public partial class GreetPage : ContentPage
{
    public GreetPage()
    {
        On<iOS>().SetUseSafeArea(true);

        InitializeComponent();

        listView.ItemsSource = new List<Contact>
        {
            new Contact { Name="John", ImageUrl = "http://lorempixel.com/100/100/people/1" },
            new Contact { Name="Jack", ImageUrl = "http://lorempixel.com/100/100/people/2", Status="Hello guys" },
            new Contact { Name="Jill", ImageUrl = "http://lorempixel.com/100/100/people/3" }
        };
    }       
}

Contact.cs 类是这样的:

public class Contact
{
    public string Name { get; set; }
    public string Status { get; set; }
    public string ImageUrl { get; set; }
}

标签: xamarinxamarin.formsxamarin.android

解决方案


您的问题与对具有非安全 (http) 连接的更高 Android 版本的限制有关。

如果您调试应用程序并查看输出,您将看到如下消息:

图像加载:获取 http://lorempixel.com/100/100/people/1的流时出错:Java.IO.IOException:Java.Interop.JniEnvironment+InstanceMethods.CallVoidMethod(Java.Interop.JniObjectReference 实例,Java.Interop.JniMethodInfo 方法,Java.Interop.JniArgumentValue* args)不允许到 lorempixel.com 的明文 HTTP 流量 [ 0x00069] 在:0 在 Java.Interop.JniPeerMembers+JniInstanceMethods.InvokeAbstractVoidMethod(System.String encodedMember,Java.Interop.IJavaPeerable self,Java.Interop.JniArgumentValue* 参数)[0x00014] 在:0 在 Java.Net.HttpURLConnectionInvoker.Connect () [0x0000a] 在:0 在 Xamarin.Android.Net.AndroidClientHandler+<>c__DisplayClass44_0.b__0 () [0x0005a] 在:0 在 System.Threading.Tasks.Task.InnerInvoke () [0x0000f] 在:0 在系统。 Threading.Tasks.Task.Execute () [0x00000] 在:0 --- 从先前抛出异常的位置结束堆栈跟踪 ---

如您所见,有一条消息说Cleartext HTTP traffic to lorempixel.com not permitted at

最快的解决方案是android:usesCleartextTraffic="true"在 Manifest.xml 文件中的应用程序级别添加:

<application android:label="MyApp.Android" android:usesCleartextTraffic="true">
    ...
</application>

但上述不是推荐的,因为它在安全方面存在漏洞。最好的解决方案是https在您的网址中使用。

在此处输入图像描述

希望这可以帮助


推荐阅读