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

Xamarin.Android中Error inflating class Fragment问题求助

排查Xamarin.Android中“Error inflating class Fragment”错误

问题场景

开发Xamarin.Android应用,目标实现ListView列表项点击切换Fragment功能,编译时触发“Error inflating class Fragment”错误,相关代码如下:

Activity部分代码

public class SongListActivity : AppCompatActivity, ListView.IOnItemClickListener, ListView.IOnItemLongClickListener
{
    ....
    AndroidX.Fragment.App.FragmentManager fragmentManager;
    infoFragment infoFragment1;  
    ....
    protected override void OnCreate(Bundle savedInstanceState)
    {    
        ....  
        SetContentView(Resource.Layout.SongList);
        fragmentManager = SupportFragmentManager;
        FragmentTransaction transaction = fragmentManager.BeginTransaction();
        infoFragment1 = new infoFragment();
        transaction.Add(Resource.Id.info, infoFragment1, "tag1");
        transaction.Commit();
    }
    ....
}

Activity布局XML

<?xml version="1.0" encoding="utf-8" ?> 
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
   android:orientation="vertical"
   android:layout_width="match_parent"
   android:layout_height="match_parent"
    android:padding="5dp"
    android:background="@drawable/background3"
   >
    <androidx.appcompat.widget.Toolbar
        android:minWidth="30px"
        android:minHeight="30px"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:id="@+id/toolbar1" />

    <EditText  
        android:id="@+id/evSearch"  
        android:layout_width="fill_parent"  
        android:layout_height="40dp"  
        android:hint=" 🔍 "  
        android:inputType="textVisiblePassword"  
        android:background="#FDF3FA"
        android:layout_marginBottom="10dp"   
        android:layout_marginTop="10dp"
        android:fontFamily="serif"
        android:textColor="#000000"/>
    <fragment
        android:layout_width="match_parent"
        android:layout_height="100dp"
        android:id="@+id/fragmentinfo"
         />

   <FrameLayout
        android:layout_width="match_parent"
        android:layout_height="100dp"
        android:id="@id/info"
         />

    <ListView
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:id="@+id/listView"
        android:divider="#dddddd"
        android:dividerHeight="1dp"
        />
       
</LinearLayout>

Fragment类代码

public class infoFragment : Fragment
{
    View view;
    Communicator c;
    TextView tvTitle, tvArtists;
    ImageView iv1, iv2, iv3, iv4, iv5, iv6, iv7, iv8, iv9, iv10;
    List<Chord> list, chordlist;
    public override void OnCreate(Bundle savedInstanceState)
    {
        base.OnCreate(savedInstanceState);
        Log.Debug("app", "OnCreate fragment");
        list = new List<Chord>();
        chordlist = new List<Chord>();
        chordlist = MainActivity.chordList;
    }
    public infoFragment()
    {

    }
    public override void OnAttach(Context context)
    {
        base.OnAttach(context);

        if (context.GetType() == typeof(AppCompatActivity)){
            c = (Communicator)context;
            Log.Debug("Freddie", "Mercury");
        }
        else Log.Debug("Freddie", "mmmmm");

    }
    public override View OnCreateView(LayoutInflater inflater, ViewGroup container,
                Bundle savedInstanceState)
    {
        View view = inflater.Inflate(Resource.Layout.fragment_info, container, false);
        tvTitle = (TextView)view.FindViewById(Resource.Id.tvFragment);
        tvArtists = (TextView)view.FindViewById(Resource.Id.tvArtist);
        iv1 = (ImageView)view.FindViewById(Resource.Id.iv1);
        iv2 = (ImageView)view.FindViewById(Resource.Id.iv2);
        iv3 = (ImageView)view.FindViewById(Resource.Id.iv3);
        iv4 = (ImageView)view.FindViewById(Resource.Id.iv4);
        iv5 = (ImageView)view.FindViewById(Resource.Id.iv5);
        iv6 = (ImageView)view.FindViewById(Resource.Id.iv6);
        iv7 = (ImageView)view.FindViewById(Resource.Id.iv7);
        iv8 = (ImageView)view.FindViewById(Resource.Id.iv8);
        iv9 = (ImageView)view.FindViewById(Resource.Id.iv9);
        iv10 = (ImageView)view.FindViewById(Resource.Id.iv10);
        return view;

    }
    public override void OnActivityCreated(Bundle savedInstanceState)
    {
        base.OnActivityCreated(savedInstanceState);
        Log.Debug("app", "OnActivityCreated");
    }
    public List<Chord> convertStringToList()
    {
        List<Chord> l = new List<Chord>();
        string ch = "";
        string cl = "";
        cl = AddNewSongActivity.cl;
        for (int i = 0; i < cl.Length; i++)
        {
            while (cl[i] != '/')
            {
                ch += cl[i];
            }
            foreach (var item in chordlist)
            {
                if (item.getChordName() == ch)
                    l.Add(item);
            }
            ch = "";
        }
        return l;
    }
    public override void OnStart()
    {
        base.OnStart();
        Log.Debug("app", "OnStart activity");
    }
    public override void OnResume()
    {
        base.OnResume();
        Log.Debug("app", "OnResume activity");

    }
    public void displaySong(Song s)
    {
        tvTitle.Text = s.getSongName();
        tvArtists.Text = s.GetArtistName();
        list = convertStringToList();
        displayChords(s);

    }
}

错误原因分析

  1. 静态Fragment标签未指定类名:布局XML中的<fragment>标签没有设置android:name属性,系统无法确定要加载的Fragment类,导致Inflate失败。你是通过代码动态添加Fragment到FrameLayout,这个静态<fragment>标签属于冗余配置,直接删除即可。
  2. FrameLayout的ID写法错误:android:id="@id/info"应该改为android:id="@+id/info",@+id用于创建新的ID资源,@id仅用于引用已存在的ID。

修复方案

步骤1:修改Activity布局XML

删除冗余的<fragment>标签,并修正FrameLayout的ID:

<?xml version="1.0" encoding="utf-8" ?> 
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
   android:orientation="vertical"
   android:layout_width="match_parent"
   android:layout_height="match_parent"
    android:padding="5dp"
    android:background="@drawable/background3"
   >
    <androidx.appcompat.widget.Toolbar
        android:minWidth="30px"
        android:minHeight="30px"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:id="@+id/toolbar1" />

    <EditText  
        android:id="@+id/evSearch"  
        android:layout_width="fill_parent"  
        android:layout_height="40dp"  
        android:hint=" 🔍 "  
        android:inputType="textVisiblePassword"  
        android:background="#FDF3FA"
        android:layout_marginBottom="10dp"   
        android:layout_marginTop="10dp"
        android:fontFamily="serif"
        android:textColor="#000000"/>

   <FrameLayout
        android:layout_width="match_parent"
        android:layout_height="100dp"
        android:id="@+id/info"
         />

    <ListView
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:id="@+id/listView"
        android:divider="#dddddd"
        android:dividerHeight="1dp"
        />
       
</LinearLayout>

步骤2:实现ListView点击切换Fragment

在Activity中补充OnItemClick方法,实现点击列表项切换Fragment(如果需要替换已有Fragment,使用Replace而非Add):

public void OnItemClick(AdapterView parent, View view, int position, long id)
{
    // 假设从ListView获取当前选中的Song对象
    Song selectedSong = (Song)parent.Adapter.GetItem(position);
    
    // 创建新的Fragment实例(或复用现有实例更新数据)
    infoFragment newInfoFragment = new infoFragment();
    // 传递数据给Fragment(可选,可通过Bundle)
    Bundle args = new Bundle();
    args.PutString("SongName", selectedSong.getSongName());
    args.PutString("ArtistName", selectedSong.GetArtistName());
    newInfoFragment.Arguments = args;
    
    // 执行Fragment替换操作
    FragmentTransaction transaction = fragmentManager.BeginTransaction();
    transaction.Replace(Resource.Id.info, newInfoFragment, "tag1");
    // 添加返回栈,支持返回上一个Fragment状态
    transaction.AddToBackStack(null);
    transaction.Commit();
}

步骤3:在Fragment中接收传递的数据(可选)

如果通过Bundle传递数据,在Fragment的OnCreate或OnCreateView中获取:

public override void OnCreate(Bundle savedInstanceState)
{
    base.OnCreate(savedInstanceState);
    if (Arguments != null)
    {
        string songName = Arguments.GetString("SongName");
        string artistName = Arguments.GetString("ArtistName");
        // 初始化数据显示
    }
    // 其他初始化逻辑...
}

额外注意事项

  • 确保你的Fragment继承自AndroidX.Fragment.App.Fragment,Activity继承自AppCompatActivity,并使用SupportFragmentManager(你的代码已满足此要求)。
  • 检查fragment_info.axml布局文件是否存在且无语法错误,这也是Inflate失败的常见原因之一。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.26 15:39:58