android - AppCompat v7 工具栏 "Error inflating class <unknown>"

标签 android android-actionbar toolbar android-appcompat

阅读 SO 线程后,我需要使用 AppCompat V7:21 中引入的新工具栏功能 here和 android 博客文章 here .我将博文中的工具栏 fragment 准确地复制到我的布局中:

<?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>    

问题是我得到:

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

有趣的是,如果我删除这一行: android:minHeight="?attr/actionBarSize"

它有效。所以问题不是因为项目依赖性等等。看来我只能访问 ?attr 元素,如 actionBarSize 或 colorPrimary

不必说我已经添加了 AppCompat 依赖项。并且activity继承自PreferenceActivity。这是我的毕业典礼:

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'
}

herehere人们报告随机解决问题。但是我的随机数在过去两天没有用。

编辑:

这是我的 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();
        }
    });
}

最佳答案

使用属性 (?attr/) 意味着使用当前上下文主题中的值。您需要确保您的主题对 ?attr/actionBarSize 属性有值(value)。您可以使用或继承@style/Theme.AppCompat 中的主题。或者只是手动设置值。

关于android - AppCompat v7 工具栏 "Error inflating class <unknown>",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27903000/

相关文章:

android - HTML <a/> 标签在Android中的实现

android - 我确保字符串完整性的方法安全吗?

android - 使用操作栏中的选项卡处理屏幕方向的 fragment

android - 如何防止actionMode和工具栏在它们之间切换时变为 "jump"?

emacs - 如何只在某些模式下显示工具栏?

android - MIUI中如何开启Draw Overlay权限弹窗?

java - 如何像FB Messenger一样在android中 "auto change"状态栏文本颜色?

android - 以编程方式为 ActionBarDrawerToggle 图标设置动画

android - 如何修复 ' You must specifiy a layout in the include tag: <include layout="@layout/layoutID"/>'

java - 如何在 fragment 更新时更新工具栏标题