programing tip

android.view.InflateException : 이진 XML 파일 : 클래스 조각 팽창 오류

itbloger 2020. 6. 21. 20:13
반응형

android.view.InflateException : 이진 XML 파일 : 클래스 조각 팽창 오류


설명 할 수없는 매우 실망스러운 오류가 있습니다. Android AppCompat이전 버전과 호환되도록 하는 Android 애플리케이션을 만들었습니다 . 내 주요 활동 레이아웃 파일은 다음과 같습니다.

<android.support.v4.widget.DrawerLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/drawer_layout"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity">

    <!-- As the main content view, the view below consumes the entire
         space available using match_parent in both dimensions. -->
    <FrameLayout
        android:id="@+id/container"
        android:layout_width="match_parent"
        android:layout_height="match_parent" />

    <!-- android:layout_gravity="start" tells DrawerLayout to treat
         this as a sliding drawer on the left side for left-to-right
         languages and on the right side for right-to-left languages.
         If you're not building against API 17 or higher, use
         android:layout_gravity="left" instead. -->

    <!-- The drawer is given a fixed width in dp and extends the full height of
         the container. -->
    <fragment android:id="@+id/navigation_drawer"
        android:layout_width="@dimen/navigation_drawer_width"
        android:layout_height="match_parent"
        android:layout_gravity="start"
        android:name="com.fragment.NavigationDrawerFragment" />

</android.support.v4.widget.DrawerLayout>

그리고 내 활동의 주요 코드는 다음과 같습니다.

public class MainActivity extends ActionBarActivity {
@Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
   }
}

여기서 주요 문제는 위의 코드가 거의 모든 장치 (자극 장치 또는 일부 실제 장치)에서 원활하게 실행되는 것입니다. 그러나 삼성 S3에서 실행할 때. 이 오류가 나타납니다.

java.lang.RuntimeException: Unable to start activity ComponentInfo{view.MainActivity}: android.view.InflateException: Binary XML file line #25: Error inflating class fragment
            at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2081)
            at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2106)
            at android.app.ActivityThread.access$700(ActivityThread.java:134)
            at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1217)
            at android.os.Handler.dispatchMessage(Handler.java:99)
            at android.os.Looper.loop(Looper.java:137)
            at android.app.ActivityThread.main(ActivityThread.java:4856)
            at java.lang.reflect.Method.invokeNative(Native Method)
            at java.lang.reflect.Method.invoke(Method.java:511)
            at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1007)
            at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:774)
            at dalvik.system.NativeStart.main(Native Method)
     Caused by: android.view.InflateException: Binary XML file line #25: Error inflating class fragment
            at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:704)
            at android.view.LayoutInflater.rInflate(LayoutInflater.java:746)
            at android.view.LayoutInflater.inflate(LayoutInflater.java:489)
            at android.view.LayoutInflater.inflate(LayoutInflater.java:396)
            at android.view.LayoutInflater.inflate(LayoutInflater.java:352)
            at com.android.internal.policy.impl.PhoneWindow.setContentView(PhoneWindow.java:316)
            at android.app.Activity.setContentView(Activity.java:1901)
            at android.support.v7.app.ActionBarActivity.superSetContentView(ActionBarActivity.java:208)
            at android.support.v7.app.ActionBarActivityDelegateICS.setContentView(ActionBarActivityDelegateICS.java:111)
            at android.support.v7.app.ActionBarActivity.setContentView(ActionBarActivity.java:76)

오류 수정 방법을 알려주세요. :)


디버깅을 위해 오랜 시간이 지난 후에이 문제를 해결했습니다. (아직도 이유를 설명 할 수는 없지만). 속성 android:name을로 변경했습니다 class. (Android 문서에서는 속성이 동일하지만 작동한다고 말합니다!)

따라서 다음과 같이 변경되어야합니다.

 android:name="com.fragment.NavigationDrawerFragment"

class = "com.fragment.NavigationDrawerFragment"

따라서 새로운 레이아웃은 다음과 같아야합니다.

<!-- As the main content view, the view below consumes the entire
     space available using match_parent in both dimensions. -->
<FrameLayout
    android:id="@+id/container"
    android:layout_width="match_parent"
    android:layout_height="match_parent" />

<!-- android:layout_gravity="start" tells DrawerLayout to treat
     this as a sliding drawer on the left side for left-to-right
     languages and on the right side for right-to-left languages.
     If you're not building against API 17 or higher, use
     android:layout_gravity="left" instead. -->

<!-- The drawer is given a fixed width in dp and extends the full height of
     the container. -->
<fragment android:id="@+id/navigation_drawer"
    android:layout_width="@dimen/navigation_drawer_width"
    android:layout_height="match_parent"
    android:layout_gravity="start"
    class = "com.fragment.NavigationDrawerFragment" />

이 도움을 바랍니다 :)


제공된 답변을 사용하여 문제를 해결할 수 없습니다. 마침내 나는 이것을 바꿨다.

<fragment
android:id="@+id/fragment_food_image_gallery"
android:name="ir.smartrestaurant.ui.fragment.ImageGalleryFragment"
android:layout_width="match_parent"
android:layout_height="200dp"
android:layout="@layout/fragment_image_gallery"
tools:layout="@layout/fragment_image_gallery" />

이에 :

<FrameLayout
android:id="@+id/fragment_container"
android:layout_width="match_parent"
android:layout_height="200dp" />

,

private void showGallery() {
    ImageGalleryFragment fragment = new ImageGalleryFragment()
    getSupportFragmentManager().beginTransaction()
                .replace(R.id.fragment_container, fragment)
                .commit();
    }

작동합니다.
프래그먼트 내부에서 사용하는 경우 getSupportFragmentManager 대신 getChildFragmentManager사용하십시오 .


나는 같은 문제가 있었으며 문제는이 스레드의 모든 답변을 시도했지만 아무 소용이 없었습니다. 내 솔루션은 Activity XML에 ID를 추가하지 않았다는 것입니다. 나는 그것이 중요하다고 생각하지 않았지만 그렇게했다.

그래서 활동 XML에서 나는 가지고 있었다 :

<fragment
    android:name="com.covle.hellocarson.SomeFragment"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"/>

그러나해야했다 :

<fragment
    android:id="@+id/some_fragment"
    android:name="com.covle.hellocarson.SomeFragment"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"/>

누군가 이것이 이것이 왜인지에 대해 기꺼이 의견을 말하면, 나는 모두 귀입니다. 다른 사람들에게도 이것이 도움이되기를 바랍니다.


TL / DR : 상위 레벨 레이아웃 XML에서 참조 된 단편을 작성하는 중에 예외가 발생했습니다 . 이 예외로 인해 더 높은 수준의 레이아웃 인플레이션이 실패했지만 초기 예외는보고되지 않았습니다 . 더 높은 수준의 인플레이션 실패 만 스택 추적에 나타납니다. 근본 원인을 찾으려면 초기 예외포착하고 기록해야합니다 .


오류의 초기 원인은 매우 다양 할 수 있으므로 여기에 각 개인의 문제를 해결 한 방법에 대한 답변이 너무 많습니다. 일부의 id경우 class, 또는 name속성 과 관련이있었습니다 . 다른 사람들에게는 권한 문제 또는 빌드 설정 때문이었습니다. 저에게는 문제가 해결되지 않았습니다. 대신와 drawable-ldrtl-xhdpi같은 적용 가능한 장소 대신에 존재하는 드로어 블 리소스가있었습니다 drawable.

그러나 이것들은 단지 세부 사항입니다. 큰 문제는 logcat에 나타나는 오류 메시지가 모든 예외를 시작하지 않았다는 것입니다. 높은 수준의 레이아웃 XML이 조각을 참조하면 조각 onCreateView()이 호출됩니다. 프래그먼트에서 예외가 발생onCreateView() 하면 (예 : 프래그먼트의 레이아웃 XML을 팽창시키는 동안) 상위 레벨 XML의 인플레이션이 실패합니다. 이 높은 수준의 인플레이션 실패는 오류 로그에서 예외로보고됩니다. 그러나 초기 예외는보고 될 정도로 체인을 잘 여행하지 않는 것 같습니다.

이러한 상황에서 오류 로그에 표시되지 않는 초기 예외를 노출시키는 방법이 문제입니다.

해결책은 매우 간단합니다. 조각의 내용 주위에 try/ catch블록 onCreateView()을 넣고 catch절에서 예외를 기록하십시오.

public View onCreateView(LayoutInflater inflater, ViewGroup contnr, Bundle savedInstSt) {
    try {
        mContentView = inflater.inflate(R.layout.device_detail_frag, null);
        // ... rest of body of onCreateView() ...
    } catch (Exception e) {
        Log.e(TAG, "onCreateView", e);
        throw e;
    }
}

어떤 프래그먼트 클래스 onCreateView()가이 작업을 수행 해야하는지 명확하지 않을 수 있으며 ,이 경우 문제를 일으킨 레이아웃에 사용 된 각 프래그먼트 클래스에이를 수행하십시오. 예를 들어, OP의 경우 예외가 발생한 앱의 코드는

at android.app.Activity.setContentView(Activity.java:1901)

어느

   setContentView(R.layout.activity_main);

따라서 onCreateView()layout에서 참조 된 조각 중 하나 에서 예외를 잡아야 합니다 activity_main.

필자의 경우 근본 원인 예외는

Caused by: android.content.res.Resources$NotFoundException: Resource
   "com.example.myapp:drawable/details_view" (7f02006f)  is not a
   Drawable (color or path): TypedValue{t=0x1/d=0x7f02006f a=-1
   r=0x7f02006f}

이 예외는 오류 로그에 onCreateView()명시 적으로 기록 할 때까지 오류 로그에 표시되지 않았습니다 . 일단 기록되면 문제는 진단 및 수정하기에 충분히 쉬웠습니다 ( 어떤 이유로 폴더 details_view.xml아래에만 존재 함 ldrtl-xhdpi). 열쇠는 문제의 근본 원인 인 예외를 잡아서 노출시키는 것이 었습니다.

모든 프래그먼트의 onCreateView()메소드 에서 상용구로 이것을하는 것은 아프지 않습니다 . 발견되지 않은 예외가 있으면 관계없이 활동이 중단됩니다. 유일한 차이점은에서 예외를 잡아서 기록하면 onCreateView()왜 그런 일이 발생했는지 암울하지 않을 것입니다.

추신 : 나는이 답변이 @DaveHubbard와 관련이 있다는 것을 깨달았지만 근본 원인을 찾기 위해 다른 접근법을 사용합니다 (로깅 대 디버거).


더 이상 필요하지 않을 수도 있지만, 더 많은 독자가 도움이 될 경우. 나는 정확히 동일 android.view.InflateException:...Error inflating class fragment합니다. 나는 모든 올바른 도서관을 포함시켰다. AndroidManifest.xml파일 에 하나 이상의 사용자 권한을 추가하여 해결<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>

Btw 나는 달리고 있었다 Android Studio 0.8.9 on Ubuntu 12.04.


리스너를 구현하지 않았기 때문에 같은 문제가 있습니다. 로 다음 코드를 참조하십시오 /*Add This!*/.

public class SomeActivity extends AppCompatActivity
        implements BlankFragment.OnFragmentInteractionListener /*Add this!*/ 
{
    @Override                                                  /*Add This!*/
    public void onFragmentInteraction(Uri uri){                /*Add This!*/
    }                                                          /*Add This!*/
}

참고로, 내 조각 클래스는 다음과 같습니다.

public class SomeFragment extends Fragment {

    private OnFragmentInteractionListener mListener;

    @Override
    public void onAttach(Activity activity) {
        super.onAttach(activity);
        try {
            mListener = (OnFragmentInteractionListener) activity;
        } catch (ClassCastException e) {
            throw new ClassCastException(activity.toString()
                    + " must implement OnFragmentInteractionListener");
        }
    }

    public interface OnFragmentInteractionListener {
        public void onFragmentInteraction(Uri uri);
    }
}

편집하다:

또한의 onCreate기능에 예외가있는 다른 상황에서도 이와 동일한 오류 메시지 가 나타납니다 Fragment. 나는 다음과 같은 것을 가지고있다 :

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

    int ID = getArguments().getInt("val");

    return rootView;
} 

이 조각을 재사용하기 때문에 인수를 설정하는 것을 잊었습니다. 그런 다음의 결과는 getArguments()입니다 null. 분명히, null여기 에서 포인터 예외가 발생합니다. 이와 같은 실수를 계속 주시하십시오.


NavigationDrawerFragment가 android.support.v4.app.Fragment를 확장합니까? 즉, 올바른 패키지를 가져오고 있습니까?

import android.support.v4.app.Fragment;

나는 또한이 문제가 있었다. 나는에서 가져 오기를 대체하여 그것을 해결 MainActivity하고NavigationDrawerFragment

에서

import android.app.Activity;
import android.app.ActionBar;

import android.support.v7.app.ActionBar;
import android.support.v7.app.ActionBarActivity;

활동 대신 MainActivity확장되도록 업데이트 했습니다.ActionBarActivity

public class MainActivity extends ActionBarActivity implements NavigationDrawerFragment.NavigationDrawerCallbacks

또한 ActionBar actionBar = getSupportActionBar();ActionBar를 얻는 데 사용 하십시오.

그리고 나는 다음 기능을 업데이트했다. NavigationDrawerFragment

private ActionBar getActionBar()
{
    return ((ActionBarActivity)getActivity()).getSupportActionBar();
}

이 문제에 직면하여 다음 코드를 사용하여 해결했습니다. childfragment manager를 사용하여 조각 트랜잭션을 시작했습니다.

나열한 것:

                  <fragment
                    class="com.google.android.youtube.player.YouTubePlayerSupportFragment"
                    android:id="@+id/youtube_fragment"
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"/>

이것이 내가 조각 트랜잭션을 시작한 방법입니다.

   youTubePlayerFragment = (YouTubePlayerSupportFragment) getChildFragmentManager().findFragmentById(R.id.youtube_fragment);

다음 코드는 childfragmentmanger를 사용하여 추가 한 조각을 어떻게 제거했는지 설명합니다.

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

        youTubePlayerFragment = (YouTubePlayerSupportFragment) getChildFragmentManager().findFragmentById(R.id.youtube_fragment);

        if (youTubePlayerFragment != null)
        {
            getChildFragmentManager().beginTransaction().remove(youTubePlayerFragment).commitAllowingStateLoss();
        }

        youTubePlayer = null;
    }

비슷한 문제가 발생했습니다. 오류 메시지는 실제 원인에 관계없이 종종 세부 정보를 거의 제공하지 않습니다. 그러나 더 유용한 정보를 얻는 방법을 찾았습니다. 내부 안드로이드 클래스 'LayoutInflater.java'(android.view 패키지)에는 예외를 다시 던지지 만 세부 정보를 선택하지 않는 'inflate'메서드가 있으므로 원인에 대한 정보가 손실됩니다.

AndroidStudio를 사용하고 LayoutInflator 539 행 (작업중 인 버전)에서 중단 점을 설정했습니다.이 'inflate'메소드에서 일반적인 예외에 대한 catch 블록의 첫 번째 줄입니다.

        } catch (Exception e) {
            InflateException ex = new InflateException(
                    parser.getPositionDescription()
                            + ": " + e.getMessage());
            ex.initCause(e);
            throw ex;

디버거에서 'e'를 보면 '원인'필드가 표시됩니다. 실제로 발생한 일에 대한 힌트를 제공하는 데 매우 도움이 될 수 있습니다. 예를 들어 코드에서 사용되지 않더라도 포함 된 조각의 부모에 ID가 있어야한다는 것을 알았습니다. 또는 TextView에 치수에 문제가 있습니다.


누군가가 이것을 필요로 할 경우를 대비하여. 가정 : 장치 전화를 USB 케이블에 연결하고 앱을 실행하기 위해 IDE를 읽습니다. 명령 프롬프트로 이동하여 문제를 판별하십시오. adb logcat을 입력하십시오.

그런 다음 IDE에서 앱을 시작하십시오. 당신은 예외가 될 것입니다.

제 경우 : 위젯 "Space"를 지원하지 않는 모바일 장치에 버전 2.3의 Android 앱을 배포하고있었습니다.


이 문제는 다른 클래스 (이 경우보기)를 확장하고 클래스에 필요한 모든 생성자를 가져 오지 않는 사용자 정의 클래스가있는 경우에 발생합니다.

예를 들어 : public class CustomTextView는 TextView를 확장합니다. {}

이 클래스에는 4 개의 생성자가 있으며, 하나를 놓치면 충돌이 발생합니다. 사실 롤리팝이 사용한 마지막 항목을 놓쳤습니다. 생성자를 추가하고 잘 작동했습니다.


build.gradle (app)에 다음을 추가해야합니다.

compile 'com.android.support:appcompat-v7:23.1.1'
compile 'com.android.support:design:23.1.1'

새로운 레이아웃이나 새로운 디자인 기능을 사용할 때마다 이것이 도움이되기를 바랍니다.


여기에 대한 답변 중 어느 것도 도움이되지 않은 후, 나는 내 조각 (당신의 경우 NavigationDrawerFragment)에서 onCreateView의 모든 줄을 가로 질러 움직이는 디버그 모드로 앱을 실행하기로 선택했습니다. 그리고 NullPointerException으로 인해 조각이 팽창하는 데 어려움이 있음을 알았습니다. 예 :

mySeekBar = (SeekBar) getActivity().findViewById(R.id.mySeekBar);
mySeekBar.setOnSeekBarChangeListener(this);

여기서 mySeekBar는 null로 설정되었으며 (적절한 레이아웃으로 컨트롤을 추가하지 못했기 때문에) 다음 줄은 NPE에 들어 갔으며 InflateException으로 나왔습니다. 또한 위에서 제안한 것처럼 android : name의 이름을 class로 바꿉니다.

이 문제는 위에서 언급 한 여러 가지 이유로 발생할 수 있습니다. 무엇이 잘못되었는지 알기 위해 라인 별 디버그 흐름을 권장합니다.


이것이 도움이 될지 모르겠습니다.

팽창하려고하는 레이아웃에 가지고있는 TextView 에이 문제가 있습니다 ( android.view.InflateException : 이진 XML 파일 줄 # 45 : 클래스 TextView 팽창 오류 ).

레이아웃을 팽창시킬 수없는 다음과 같은 XML 속성 android : textSize = "? android : attr / textAppearanceLarge" 를 설정했습니다.

(정확히 왜 몰라 내가 안드로이드에 조금 새로운 여전히 해요 - 덜 경험의 년 이상 ), 시스템 속성을 호출 함께 할 수있는 뭔가가있을 수 있습니다, 모든 I의 노하우가 최대한 빨리 평범한 구식을 사용하고, 나도 몰라 @ dimen / md_text_16sp ( 이것은 내 습관입니다 ), 문제가 해결되었습니다 :)

도움이 되었기를 바랍니다...


나는 이것을 4.4.2 장치에서 가지고 있었지만 5+는 괜찮 았습니다. 원인 : 사용자 정의보기의 초기화 내부에서 TextView(Context context, AttributeSet attrs, @AttrRes int defStyleAttr, @StyleRes int defStyleRes)API 21 +를 만드는 중이었습니다 .

Android Studio 2.1에는 주석이 달린 경우에도 불평하지 않습니다 TargetApi(21). 분명히 Android Studio 2.2는이를 수정하고 오류로 올바르게 표시합니다.

이것이 누군가를 돕기를 바랍니다.


이전 게시물에서 언급했듯이
이름을 바꿉니다.

android:name="com.fragment.NavigationDrawerFragment"

class = "com.fragment.NavigationDrawerFragment"

여전히, 그것은 나를 위해 작동하지 않았습니다. 그런 다음 com.fragment 부분과 클래스없이 클래스 이름을 사용했습니다. 마지막으로 변경하십시오

class = "NavigationDrawerFragment"

나는 파티에 조금 늦었지만이 답변 중 비가 내 경우에 도움이되었습니다. 내 조각에서 Google지도를 SupportMapFragmentPlaceAutocompleteFragment 로 사용 하고 있었습니다 . 모든 대답은 문제가 SupportMapFragment가 다시 작성되고 다시 그려지는 맵이라는 사실을 지적했습니다.

그러나 PlaceAutocompleteFragment에도 문제가있었습니다. 다음은 SupportMapFragmentSupportMapFragment인해이 문제에 직면 한 사람들을위한 효과적인 솔루션입니다.

 mapFragment = (SupportMapFragment) getChildFragmentManager().findFragmentById(R.id.mapFragment);
    FragmentManager fm = getChildFragmentManager();

    if (mapFragment == null) {
        mapFragment = SupportMapFragment.newInstance();
        fm.beginTransaction().replace(R.id.mapFragment, mapFragment).commit();
        fm.executePendingTransactions();
    }

    mapFragment.getMapAsync(this);

    //Global PlaceAutocompleteFragment autocompleteFragment;


    if (autocompleteFragment == null) {
        autocompleteFragment = (PlaceAutocompleteFragment) getActivity().getFragmentManager().findFragmentById(R.id.place_autoCompleteFragment);

    }

그리고 onDestroyView에서 SupportMapFragment 및 SupportMapFragment를 지우십시오.

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


    if (getActivity() != null) {
        Log.e("res","place dlted");
        android.app.FragmentManager fragmentManager = getActivity().getFragmentManager();
        android.app.FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
        fragmentTransaction.remove(autocompleteFragment);
        fragmentTransaction.commit();

        autocompleteFragment = null;
    }


}

After long time of tries, this is how I solved the problem after none of the above answers could.

  1. Extend AppCompatActivity for your Main activity instead of Activity.
  2. Add android:theme="@style/Theme.AppCompat.Light" to your <Activity..../> in the AndroidManifest.xml
  3. In your NavigationDrawerFragment Class, change your ActionBar instances to

    ActionBar mActionBar=((AppCompatActivity)getActivity()).getSupportActionBar();
    

EDIT

It should be a consistency between the Activity and Layout. If the Layout has one of the AppCompat Theme such like Theme.AppCompat.Light, your Activity should extends AppCompatActivity.

I wanted to have the burger icon and a Navigation Drawer that looks like the Android Gmail App, but I ended up with an ugly Navigation Drawer. All that because all my Classes extends Activity instead of AppCompatActivity.

I re-factored the entire project to extend AppCompatActivity, then Right-Click on the Layout Folder, chose new -> Activity then Navigation Drawer Activity and Boom, everything is done for me!


I think the basic problem is with "android:targetSdkVersion" which is defined in AndroidManifest.xml. In my case, the initial value which I have defined as:

android:targetSdkVersion=16

I changed it to:

android:targetSdkVersion=22

which resolved my all of the error. So, setting up the correct "targetSdkVersion" is also important before building an android app.


In case someone else comes here and the answers do not help solve the problem, one more thing to try.

As others have mentioned, this usually is caused by an issue nested in the XML itself as opposed to something you did wrong in your Java. In my case, it was a super easy (and stupid) mistake to fix.

I had code like this:

<view
    android:layout_width="fill_parent"
    android:layout_height="1dip"
    android:id="@+id/view44"
    android:background="@color/gray"
    />

When all I had to do was capitalize the v in 'View' so that the system recogized it. Check that your custom views (Or Fragments, recyclerviews, etc) all have the proper capitalized declaration up front so that the XML auto-complete will match it to the appropriate view.


For some of you that still haven't found a solution for this, in my case it was happening because I had an OOM (Out of Memory) issue. This can happen when you have for example a memory leak in your app when using it for a long time. In my stack trace, this was the main reason.


I had this error too, and after very long debugging the problem seamed to be that my MainClass extended Activity instead of FrameActivity, in my case, the xml wasn't a problem. Hope to help you.


In my case .

The layout i was trying to inflate had

<include 
 layout  = "...."
/>

tag, removing it fixed it.

I was trying to inflate a previous layout designed for a Actvity into the view-pager adapter.


My error was caused by a different problem.

I was passing a bundle from an Activity to its fragment. When I commented the code receiving the bundle in the fragment the error was gone. As it turns out, my error was due to the below "getArguments();" part which was returning null.

Bundle args = getArguments();

Upon checking the Activity sending code, I realized I had a silly mistake in the below;

Bundle bundle =new Bundle();
 bundle.putInt("recipeID", recipe_position);
 Fragment mainFragment = new MainActivityFragment();
 mainFragment.setArguments(bundle);
 FragmentManager fragmentManager = getSupportFragmentManager();
 --> fragmentManager.beginTransaction()
                        .replace(R.id.container, new  MainActivityFragment(),
                                DetailRecipeActivityFragment.TAG)
                        .commit();

I was creating a NEW fragment in the line with the arrow. Whereas I should have used the pre-instantiated fragment that already had my bundle. So it should have been:

Bundle bundle =new Bundle();
 bundle.putInt("recipeID", recipe_position);
 Fragment mainFragment = new MainActivityFragment();
 mainFragment.setArguments(bundle);
 Fragment mainFragment = new MainActivityFragment();
 FragmentManager fragmentManager = getSupportFragmentManager();
 -->fragmentManager.beginTransaction()
                        .replace(R.id.container, mainFragment,
                                DetailRecipeActivityFragment.TAG)
                        .commit();

I don't know why exactly it throws this error instead of an NPE, but this solved my error in case someone is having the same scenario


I was having the same problem, in my case the package name was wrong, fixing it solved the problem.


Open the gradle.properties and add the following line:

android.enableAapt2=false

Reference: https://github.com/chrisjenx/Calligraphy/issues/417#issuecomment-365177808


I had this error when I had my RecyclerView at the root of my fragment.xml,

but when I wrapped it with a ViewGroup, the app worked fine.

참고URL : https://stackoverflow.com/questions/19874882/android-view-inflateexception-binary-xml-file-error-inflating-class-fragment

반응형