如何在xamarin.android

时间:2019-06-07 22:30:55

标签: xamarin.forms xamarin.android

我必须将一些带有HTML图像的HTML代码从网站加载到Label。我自定义了一个标签来显示HTML代码,如果它没有img,它会很好地工作,但是当它带有img时,它会显示一个小方块。因此,我在互联网上寻找并发现了类似我必须实现Html.IImageGetter的结果。 因此,此代码自定义标签:

protected override void OnElementChanged(ElementChangedEventArgs<Label> e)
    {
        base.OnElementChanged(e);
        if (!string.IsNullOrEmpty(Element.Text))
            Control?.SetText(GetText(), TextView.BufferType.Spannable);
    }


    protected override void OnElementPropertyChanged(object sender, PropertyChangedEventArgs e)
    {
        base.OnElementPropertyChanged(sender, e);

        if (e.PropertyName == Label.TextProperty.PropertyName)
        {
            if (!string.IsNullOrEmpty(Element.Text))
                Control?.SetText(GetText(), TextView.BufferType.Spannable);

        }
    }

    [Obsolete]
    private ISpanned GetText()
    {
        //renderimg.GetDrawable(Element.Text);
        return (int)Build.VERSION.SdkInt >= 24
            ?Html.FromHtml(Element.Text, FromHtmlOptions.ModeLegacy,new renderimg(), null)
            : Html.FromHtml(Element.Text, new renderimg(), null);
    }

这是Html.IImageGetter的

 public Drawable GetDrawable(string source)
    {
        Drawable drawable;
        Bitmap bitMap;
        BitmapFactory.Options bitMapOption;
        try
        {
            bitMapOption = new BitmapFactory.Options();
            bitMapOption.InJustDecodeBounds = false;
            bitMapOption.InPreferredConfig = Bitmap.Config.Argb4444;
            bitMapOption.InPurgeable = true;
            bitMapOption.InInputShareable = true;
            var url = new Java.Net.URL(source);

            bitMap = BitmapFactory.DecodeStream(url.OpenStream(), null, bitMapOption);
            drawable = new BitmapDrawable(bitMap);
            //var url = new Java.Net.URL(source);
            //drawable =  Drawable.CreateFromStream(url.OpenStream(), null);
        }
        catch (Exception ex)
        {
            return null;
        }

        drawable.SetBounds(0, 0, bitMapOption.OutWidth, bitMapOption.OutHeight);
        return drawable;
    }

并显示错误:

  

Android.OS.NetworkOnMainThreadException:类型的异常   引发了“ Android.OS.NetworkOnMainThreadException”。在   Java.Interop.JniEnvironment + InstanceMethods.CallObjectMethod   (Java.Interop.JniObjectReference实例,Java.Interop.JniMethodInfo   方法,Java.Interop.JniArgumentValue * args)[0x00069]在   <9ed4c1a7b8844cdcb5330cc881c1cd6a>:0在   Java.Interop.JniPeerMembers + JniInstanceMethods.InvokeAbstractObjectMethod   (System.String编码的成员,Java.Interop.IJavaPeerable自我,   Java.Interop.JniArgumentValue *参数)[0x00014]在   Java.Net.URL.OpenStream上的<9ed4c1a7b8844cdcb5330cc881c1cd6a>:0   [0x0000a]在:0处   NewsApp.Droid.renderimg.GetDrawable(System.String源)[0x00033]

0 个答案:

没有答案