代码之家  ›  专栏  ›  技术社区  ›  Christian

为什么在XML中集成一个片段失败,错误消息是无法将片段转换为视图?

  •  0
  • Christian  · 技术社区  · 7 年前

    我想创建一个片段,我可以在多个活动中用作backbutton(我知道android有自己的backbutton,但对于我来说有一个特定的UI很重要)。

    我尝试通过添加XML将backbutton集成到appcompatactivity中:

    <android.support.v4.app.Fragment
        android:name="com.myapp.uielements.BackButton"
        android:id="@+id/backbutton"
        android:layout_height="wrap_content"
        android:layout_width="wrap_content"/>
    

    后按钮的代码为:

    import android.support.v4.app.Fragment;
    ...
    
    public class BackButton extends Fragment {
        @Override
        public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
            View rootView = inflater.inflate(R.layout.backbutton, container, false);
    
            rootView.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    getActivity().finish();
                }
            });
    
            return rootView;
        }
    }
    

    我得到错误:

     Caused by: android.view.InflateException: Binary XML file line #48: Binary XML file line #48: Class is not a View android.support.v4.app.Fragment
     Caused by: android.view.InflateException: Binary XML file line #48: Class is not a View android.support.v4.app.Fragment
     Caused by: java.lang.ClassCastException: class android.support.v4.app.Fragment cannot be cast to android.view.View
    
    1 回复  |  直到 7 年前
        1
  •  1
  •   laalto    7 年前

    android.support.v4.app.Fragment 类名称不是 View 。布局充气机期望看到 视图 或特殊标签,如 fragment 。要通过XML布局实例化片段,请使用 片段 :

    <fragment android:name="com.myapp.uielements.BackButton" ...