【问题标题】:Error inflating class fragment error错误膨胀类片段错误
【发布时间】:2012-11-21 13:47:30
【问题描述】:

我有一个包含两个主要细节片段的主要活动。我正在尝试像"Multiple fragments, multiple activities" 方法一样实现。

布局文件夹 activity_main.xml

<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MoneyActivity"
    android:id="@+id/fragment_container" >
 <fragment class="com.mysite.money.AFragment"
              android:id="@+id/AFragment"
              android:layout_width="match_parent"
              android:layout_height="match_parent"/>
 </FrameLayout>

layout-large 文件夹 activity_main.xml

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MoneyActivity"
    android:id="@+id/fragment_container"
    android:orientation="horizontal" >


   <fragment class="com.mysite.money.AFragment"
              android:id="@+id/AFragment"
              android:layout_width="@dimen/action_bar_title_text_size"
              android:layout_height="match_parent"/>

   <fragment class="com.mysite.money.BFragment"
              android:id="@+id/BFragment"
              android:layout_width="match_parent"
              android:layout_height="match_parent"/>


 </LinearLayout>

我收到如下错误(在 tablet-layout-large 上运行时):

java.lang.RuntimeException: Unable to start activity ComponentInfo{com.mysite.money/com.mysite.money.MoneyActivity}: android.view.InflateException: Binary XML file line #15: Error inflating class fragment

我正确检查了片段的类名。

我认为我收到错误 BFragment

BF片段: 公共类 BFragment 扩展 SherlockFragment {

    String selectedItem="";

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        int size = getArguments().size();
        if(size>0)
        {
            selectedItem = getArguments().getString("position").toString();
        }
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,Bundle savedInstanceState) {
        TextView textView=new TextView(inflater.getContext());
        textView.setText("Selected Item->"+selectedItem);
        return textView;
    }

}

我的 mainActivity 中的 OnItemSelected(与片段 A 关联)

**@Override
    public void onItemSelected(String id) {
          BFragment displayFrag = (BFragment) getSupportFragmentManager().findFragmentById(new BFragment().getId());
        if (displayFrag == null) {
            // DisplayFragment (Fragment B) is not in the layout (handset layout),
            // so start DisplayActivity (Activity B)
            // and pass it the info about the selected item
            Intent intent = new Intent(this, BActivity.class);
            intent.putExtra("position", id);
            Log.i("innodea", "position->"+id);
            startActivity(intent);

        } else {
            // DisplayFragment (Fragment B) is in the layout (tablet layout),
            // so tell the fragment to update
            //displayFrag.updateContent(id);
        }
    }**

片段:

public class AFragment extends SherlockListFragment {

    private View inflate;
    private Callbacks mCallbacks = sDummyCallbacks;
    private int mActivatedPosition= ListView.INVALID_POSITION;
    private static final String STATE_ACTIVATED_POSITION = "activated_position";

    public interface Callbacks {
        public void onItemSelected(String id);
    }

    /**
     * A dummy implementation of the {@link Callbacks} interface that does
     * nothing. Used only when this fragment is not attached to an activity.
     */
    private static Callbacks sDummyCallbacks = new Callbacks() {
        public void onItemSelected(String id) {
        }
    };

    @Override
    public void onAttach(Activity activity) {
        super.onAttach(activity);
        // Activities containing this fragment must implement its callbacks.
        if (!(activity instanceof Callbacks)) {
            throw new IllegalStateException(
                    "Activity must implement fragment's callbacks.");
        }

        mCallbacks = (Callbacks) activity;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setListAdapter(new ArrayAdapter<DummyContent.DummyItem>(getActivity(),android.R.layout.simple_list_item_activated_1,android.R.id.text1, DummyContent.ITEMS));
    }

    @Override
    public void onViewCreated(View view, Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);

        // Restore the previously serialized activated item position.
        if (savedInstanceState != null
                && savedInstanceState.containsKey(STATE_ACTIVATED_POSITION)) {
            setActivatedPosition(savedInstanceState
                    .getInt(STATE_ACTIVATED_POSITION));
        }
    }



    @Override
    public void onDetach() {
        super.onDetach();

        // Reset the active callbacks interface to the dummy implementation.
        mCallbacks = sDummyCallbacks;
    }

    @Override
    public void onListItemClick(ListView listView, View view, int position,long id) {
        super.onListItemClick(listView, view, position, id);

        // Notify the active callbacks interface (the activity, if the
        // fragment is attached to one) that an item has been selected.
        mCallbacks.onItemSelected(DummyContent.ITEMS.get(position).id);
    }

    @Override
    public void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
        if (mActivatedPosition != ListView.INVALID_POSITION) {
            // Serialize and persist the activated item position.
            outState.putInt(STATE_ACTIVATED_POSITION, mActivatedPosition);
        }
    }

    /**
     * Turns on activate-on-click mode. When this mode is on, list items will be
     * given the 'activated' state when touched.
     */
    public void setActivateOnItemClick(boolean activateOnItemClick) {
        // When setting CHOICE_MODE_SINGLE, ListView will automatically
        // give items the 'activated' state when touched.
        getListView().setChoiceMode(
                activateOnItemClick ? ListView.CHOICE_MODE_SINGLE
                        : ListView.CHOICE_MODE_NONE);
    }

    private void setActivatedPosition(int position) {
        if (position == ListView.INVALID_POSITION) {
            getListView().setItemChecked(mActivatedPosition, false);
        } else {
            getListView().setItemChecked(position, true);
        }

        mActivatedPosition = position;
    }

}

【问题讨论】:

标签: android android-fragments


【解决方案1】:

如果您在调用onActivityCreated() 之前在片段内使用getActivity() 进行操作,则可能会发生异常android.view.InflateException: Binary XML file line: #... Error inflating class fragment。在这种情况下,您会收到错误的活动参考并且不能依赖它。

例如下一个模式是错误的:

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, 
        Bundle savedInstanceState) 
{
    final View view = inflater.inflate(R.layout..., container, false);

    Button button = getActivity().findViewById(R.id...);
    button.setOnClickListener(...); - another problem: button is null

    return view;
}

【讨论】:

    【解决方案2】:

    需要为静态片段添加唯一 ID。我在仔细查看日志中的错误后找到了它。点击以下链接查看错误详情:

    Error Inspection in logs

    不需要许多帖子中建议的 FragmentActivity。 AppCompatActivity 很好。 所以,像下面这样的代码就可以了。

    <?xml version="1.0" encoding="utf-8"?>
    <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:orientation="vertical">
    
        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginBottom="10dp"
            android:text="Customize your Android: " />
    
        <fragment xmlns:android="http://schemas.android.com/apk/res/android"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:name="com.example.android.android_me.ui.MasterListFragment"
            android:id="@+id/StaticFragment"/>
    
    </LinearLayout>
    

    【讨论】:

      【解决方案3】:

      您的片段代码很可能已损坏,并且在创建时崩溃,最终导致通货膨胀失败。在每个片段上设置断点onCreateView() 和片段创建期间调用的相关方法,或者尝试手动实例化片段 (new AFragment()) 并将其附加到布局以查看失败的确切位置。

      【讨论】:

        【解决方案4】:

        您需要从android.support.v4.app.Fragment 导入Fragment 类而不是android.app.Fragment

        import android.support.v4.app.Fragment;
        

        并且在你打算使用这个片段的activity的XML文件中,你需要使用:

                <fragment
                android:layout_width="match_parent"
                android:layout_height="match_parent"
                android:id="@+id/map_fragment"
                name="yourpackagname.yourfragmentclass"/>
                //package name here, is the name of folder which is in java directory.
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2014-02-16
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2014-03-24
          相关资源
          最近更新 更多