AppCompat v7 Toolbar “Error inflating class

2019-08-14 16:16发布

问题:

I need to use new Toolbar feature introduced in AppCompat V7:21 after reading SO thread here and android blog post here. I exacctly copied Toolbar snippet from the blogpost to my layout:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical">

    <android.support.v7.widget.Toolbar                  <- Line 8
        android:layout_height="wrap_content"
        android:layout_width="match_parent"
        android:minHeight="?attr/actionBarSize"
        app:theme="@style/ThemeOverlay.AppCompat.ActionBar" />

</LinearLayout>    

The problem is that I get :

java.lang.RuntimeException: Unable to start activity ComponentInfo{com.blabla.PrefActivity}: android.view.InflateException: Binary XML file line #8: Error inflating class <unknown>    

Interestingly, if I remove this line: android:minHeight="?attr/actionBarSize"

it works. So the problem is not because of project dependencies or so. It seems I only cannot access ?attr elements like actionBarSize or colorPrimary

Not neede to say that I have already added AppCompat dependency. And the activity is inherited from PreferenceActivity. here's my gradle:

dependencies {
compile fileTree(include: ['*.jar'], dir: 'libs')
compile 'com.android.support:support-v4:21.0.3'
compile 'com.android.support:appcompat-v7:21.0.3'
}

here and here people reported to solve the issue on a random basis. But my random didn't work for past two days.

EDIT:

here is my activity:

public class PrefActivity extends PreferenceActivity {

private Toolbar mToolbar;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    ViewGroup root = (ViewGroup) findViewById(android.R.id.content);
    LinearLayout content = (LinearLayout) root.getChildAt(0);
    LinearLayout toolbarContainer = (LinearLayout) View.inflate(this, R.layout.activity_prefs, null);

    root.removeAllViews();
    toolbarContainer.addView(content);
    root.addView(toolbarContainer);

    mToolbar = (Toolbar) toolbarContainer.findViewById(R.id.toolbar);
    selectResource();
    mToolbar.setNavigationIcon(R.drawable.abc_ic_ab_back_mtrl_am_alpha);
    mToolbar.setNavigationOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            finish();
        }
    });
}

回答1:

Using of attributes (?attr/) means using of values from theme of current Context. You need to be sure that your theme has value for ?attr/actionBarSize attibute. You can use or inherit your theme from @style/Theme.AppCompat. Or just set value manually.