You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

.NET Android中如何用XmlReader从XML字符串创建IAttributeSet?

问题原因与解决方案

问题1:AttributeCount返回0的原因

你创建的XmlReader初始状态并未指向XML中的元素节点,必须先调用xmlReader.Read()方法移动到<PlayerView>元素位置,才能读取到该元素的属性。否则AttributeCount自然为0。

问题2:ClassCastException的原因

Android的Xml.AsAttributeSet方法要求传入Android原生的XmlPullParser,而你使用的是.NET框架的XmlReader,转换后得到的XmlPullAttributes类型无法被ExoPlayer构造函数所需的XmlBlock$Parser类型兼容,因此抛出类型转换异常。

正确创建IAttributeSet的两种方法

方法一:通过布局XML文件加载(推荐)

这种方式符合Android开发的常规流程,避免手动解析XML的问题:

  1. 在Resources/layout目录下新建player_view_layout.xml,内容如下:
<?xml version="1.0" encoding="utf-8"?>
<Com.Google.Android.Exoplayer2.UI.StyledPlayerView
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:id="@+id/player_view"
    app:surface_type="texture_view"
    android:layout_width="match_parent"
    android:layout_height="match_parent"/>
  1. 在MainActivity中通过LayoutInflater加载布局:
protected override void OnCreate(Bundle? savedInstanceState)
{
    base.OnCreate(savedInstanceState);
    // 加载布局
    var view = LayoutInflater.Inflate(Resource.Layout.player_view_layout, null);
    var styledPlayerView = view.FindViewById<Com.Google.Android.Exoplayer2.UI.StyledPlayerView>(Resource.Id.player_view);
    // 后续使用playerView
    SetContentView(view);
}

方法二:手动构建AttributeSet(动态设置属性)

如果需要动态创建属性,可使用Android原生的AttributeSet.Builder来构建:

protected override void OnCreate(Bundle? savedInstanceState)
{
    base.OnCreate(savedInstanceState);
    
    var attributeSetBuilder = new Android.Util.AttributeSet.Builder(this);
    // 添加android命名空间的属性
    attributeSetBuilder.AddAttribute(Android.Resource.Attribute.LayoutWidth, "match_parent");
    attributeSetBuilder.AddAttribute(Android.Resource.Attribute.LayoutHeight, "match_parent");
    // 添加app命名空间的属性
    string appNamespace = "http://schemas.android.com/apk/res-auto";
    attributeSetBuilder.AddAttribute(appNamespace, "surface_type", "texture_view");
    
    Android.Util.IAttributeSet attributes = attributeSetBuilder.Build();
    var styledPlayerView = new Com.Google.Android.Exoplayer2.UI.StyledPlayerView(this, attributes);
    
    SetContentView(styledPlayerView);
}

内容的提问来源于stack exchange,提问作者mike

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.24 04:18:11