2016-09-27 2 views
2

Видел несколько подобных потоков, но ни один и тот же или с решением.Вам нужно использовать тему theme.appcompat - но я, не так ли?

Попытка собрать простой примерный проект, чтобы понять реализацию navigationView.

Ошибка в соответствии с заголовком, мне говорят, что я должен использовать тему appcompat. Но насколько я вижу, я использую один !?

В моем файле стиля «Theme.AppCompat.Light.NoActionBar», и это указано в манифесте.

Уверен, что мне не хватает чего-то простого, но, будучи нубом для всего этого java-android malarkey, мой глаз не совсем видит это.

Действительно цените кого-то, указывающего, что мне не хватает !!

На стороне примечания .... Кажется странным для меня, что проблема с стилем вызвала мое приложение для сбоя, не должно быть стилей «внешний вид» не «функция»?

build.gradle

apply plugin: 'com.android.application' 

android { 
    compileSdkVersion 21 
    buildToolsVersion "21.1.0" 

    defaultConfig { 
     applicationId "com.mycompany.myapp2" 
     minSdkVersion 14 
     targetSdkVersion 21 
     versionCode 1 
     versionName "1.0" 
    } 
    buildTypes { 
    release { 
     minifyEnabled false 
     proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro' 
     } 
    } 
} 
dependencies { 
    compile fileTree(dir: 'libs', include: ['*.jar']) 
    compile 'com.android.support:appcompat-v7:23.1.1.aar' 
    compile 'com.android.support:design:23.1.1' 
} 

manifest.xml

<application 
    android:allowBackup="true" 
    android:icon="@drawable/ic_launcher" 
    android:label="@string/app_name" 
    android:theme="@style/AppTheme" > 
    <activity 
     android:name=".MainActivity" 
     android:label="@string/app_name" > 
     <intent-filter> 
      <action android:name="android.intent.action.MAIN" /> 

      <category android:name="android.intent.category.LAUNCHER" /> 
     </intent-filter> 
    </activity> 
</application> 

разреш/значения/style.xml

<resources> 
    <style name="AppTheme" parent="Theme.AppCompat.Light.NoActionBar"> 
     <item name="colorPrimary">#673AB7</item> 
     <item name="colorPrimaryDark">#512DA8</item> 
     <item name="colorAccent">#FF4081</item> 
    </style> 
</resources> 

разреш/меню/drawer_view.xml

<group android:checkableBehavior="single"> 
    <item 
     android:id="@+id/nav_first_fragment" 
     android:icon="@drawable/ic_one" 
     android:title="First" /> 
    <item 
     android:id="@+id/nav_second_fragment" 
     android:icon="@drawable/ic_two" 
     android:title="Second" /> 
    <item 
     android:id="@+id/nav_third_fragment" 
     android:icon="@drawable/ic_three" 
     android:title="Third" /> 
</group> 

разреш/макет/toolbar.xml

<android.support.v7.widget.Toolbar 
    xmlns:android="http://schemas.android.com/apk/res/android" 
    xmlns:app="http://schemas.android.com/apk/res-auto" 
android:id="@+id/toolbar" 
android:layout_height="wrap_content" 
android:layout_width="match_parent" 
android:fitsSystemWindows="true" 
android:minHeight="?attr/actionBarSize" 
app:theme="@style/ThemeOverlay.AppCompat.Dark.ActionBar" 
android:background="?attr/colorPrimaryDark"> 

main.xml

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

    <LinearLayout 
     android:layout_width="match_parent" 
     android:layout_height="match_parent" 
     android:orientation="vertical"> 

     <include 
      layout="@layout/toolbar" 
      android:layout_width="match_parent" 
      android:layout_height="wrap_content" /> 

     <FrameLayout 
      android:id="@+id/flContent" 
      android:layout_width="match_parent" 
      android:layout_height="match_parent" /> 
    </LinearLayout> 

    <android.support.design.widget.NavigationView 
     android:id="@+id/nvView" 
     android:layout_width="wrap_content" 
     android:layout_height="match_parent" 
     android:layout_gravity="start" 
     android:background="@android:color/white" 
     app:menu="@menu/drawer_view" /> 
</android.support.v4.widget.DrawerLayout> 

main_activity.java журнал

package com.mycompany.myapp2; 
import android.app.*; 
import android.os.*; 
import android.support.v4.widget.DrawerLayout; 
import android.support.v7.app.AppCompatActivity; 
import android.support.design.widget.NavigationView; 
import android.support.v7.app.ActionBarDrawerToggle; 
import android.support.v4.view.GravityCompat; 
import android.support.v7.widget.Toolbar; 
import android.view.MenuItem; 

public class MainActivity extends AppCompatActivity { 
    private DrawerLayout mDrawer; 
    private Toolbar toolbar; 
    private NavigationView nvDrawer; 
    private ActionBarDrawerToggle drawerToggle; 


    @Override 
    protected void onCreate(Bundle savedInstanceState) { 
     super.onCreate(savedInstanceState); 
     setContentView(R.layout.main); 

     // Set a Toolbar to replace the ActionBar. 
     toolbar = (Toolbar) findViewById(R.id.toolbar); 
     setSupportActionBar(toolbar); 

     // Find our drawer view 
     mDrawer = (DrawerLayout) findViewById(R.id.drawer_layout); 
    } 

    @Override 
    public boolean onOptionsItemSelected(MenuItem item) { 
     // The action bar home/up action should open or close the drawer. 
     switch (item.getItemId()) { 
      case android.R.id.home: 
       mDrawer.openDrawer(GravityCompat.START); 
       return true; 
     } 

     return super.onOptionsItemSelected(item); 
    } 

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

Err:

09-27 20:04:08.195 11972 11972 E AndroidRuntime        Process: com.mycompany.myapp2, PID: 11972 
09-27 20:04:08.195 11972 11972 E AndroidRuntime        java.lang.RuntimeException: Unable to start activity ComponentInfo{com.mycompany.myapp2/com.mycompany.myapp2.MainActivity}: android.view.InflateException: Binary XML file line #18: Binary XML file line #18: Error inflating class android.support.design.widget.NavigationView 
09-27 20:04:08.195 11972 11972 E AndroidRuntime        at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2426) 
09-27 20:04:08.195 11972 11972 E AndroidRuntime        at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2490) 
09-27 20:04:08.195 11972 11972 E AndroidRuntime        at android.app.ActivityThread.-wrap11(ActivityThread.java) 
09-27 20:04:08.195 11972 11972 E AndroidRuntime        at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1354) 
09-27 20:04:08.195 11972 11972 E AndroidRuntime        at android.os.Handler.dispatchMessage(Handler.java:102) 
09-27 20:04:08.195 11972 11972 E AndroidRuntime        at android.os.Looper.loop(Looper.java:148) 
09-27 20:04:08.195 11972 11972 E AndroidRuntime        at android.app.ActivityThread.main(ActivityThread.java:5443) 
09-27 20:04:08.195 11972 11972 E AndroidRuntime        at java.lang.reflect.Method.invoke(Native Method) 
09-27 20:04:08.195 11972 11972 E AndroidRuntime        at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:728) 
09-27 20:04:08.195 11972 11972 E AndroidRuntime        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:618) 
09-27 20:04:08.195 11972 11972 E AndroidRuntime        Caused by: android.view.InflateException: Binary XML file line #18: Binary XML file line #18: Error inflating class android.support.design.widget.NavigationView 
09-27 20:04:08.195 11972 11972 E AndroidRuntime        at android.view.LayoutInflater.inflate(LayoutInflater.java:539) 
09-27 20:04:08.195 11972 11972 E AndroidRuntime        at android.view.LayoutInflater.inflate(LayoutInflater.java:423) 
09-27 20:04:08.195 11972 11972 E AndroidRuntime        at android.view.LayoutInflater.inflate(LayoutInflater.java:374) 
09-27 20:04:08.195 11972 11972 E AndroidRuntime        at com.android.internal.policy.PhoneWindow.setContentView(PhoneWindow.java:393) 
09-27 20:04:08.195 11972 11972 E AndroidRuntime        at android.app.Activity.setContentView(Activity.java:2170) 
09-27 20:04:08.195 11972 11972 E AndroidRuntime        at com.mycompany.myapp2.MainActivity.onCreate(MainActivity.java:28) 
09-27 20:04:08.195 11972 11972 E AndroidRuntime        at android.app.Activity.performCreate(Activity.java:6245) 
09-27 20:04:08.195 11972 11972 E AndroidRuntime        at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1130) 
09-27 20:04:08.195 11972 11972 E AndroidRuntime        at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2379) 
09-27 20:04:08.195 11972 11972 E AndroidRuntime        ... 9 more 
09-27 20:04:08.195 11972 11972 E AndroidRuntime        Caused by: android.view.InflateException: Binary XML file line #18: Error inflating class android.support.design.widget.NavigationView 
09-27 20:04:08.195 11972 11972 E AndroidRuntime        at android.view.LayoutInflater.createView(LayoutInflater.java:645) 
09-27 20:04:08.195 11972 11972 E AndroidRuntime        at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:764) 
09-27 20:04:08.195 11972 11972 E AndroidRuntime        at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:704) 
09-27 20:04:08.195 11972 11972 E AndroidRuntime        at android.view.LayoutInflater.rInflate(LayoutInflater.java:835) 
09-27 20:04:08.195 11972 11972 E AndroidRuntime        at android.view.LayoutInflater.rInflateChildren(LayoutInflater.java:798) 
09-27 20:04:08.195 11972 11972 E AndroidRuntime        at android.view.LayoutInflater.inflate(LayoutInflater.java:515) 
09-27 20:04:08.195 11972 11972 E AndroidRuntime        ... 17 more 
09-27 20:04:08.195 11972 11972 E AndroidRuntime        Caused by: java.lang.reflect.InvocationTargetException 
09-27 20:04:08.195 11972 11972 E AndroidRuntime        at java.lang.reflect.Constructor.newInstance(Native Method) 
09-27 20:04:08.195 11972 11972 E AndroidRuntime        at android.view.LayoutInflater.createView(LayoutInflater.java:619) 
09-27 20:04:08.195 11972 11972 E AndroidRuntime        ... 22 more 
09-27 20:04:08.195 11972 11972 E AndroidRuntime        Caused by: java.lang.IllegalArgumentException: You need to use a Theme.AppCompat theme (or descendant) with the design library. 
09-27 20:04:08.195 11972 11972 E AndroidRuntime        at android.support.design.widget.ThemeUtils.checkAppCompatTheme(ThemeUtils.java:34) 
09-27 20:04:08.195 11972 11972 E AndroidRuntime        at android.support.design.widget.NavigationView.<init>(NavigationView.java:100) 
09-27 20:04:08.195 11972 11972 E AndroidRuntime        at android.support.design.widget.NavigationView.<init>(NavigationView.java:94) 
09-27 20:04:08.195 11972 11972 E AndroidRuntime        ... 24 more 
+0

У вас возникли какие-либо ошибки? –

+0

Вы включили все, кроме самой важной части: ваш манифест, где вы объявляете свой '' и какую тему он использует. – ianhanniballake

+0

Вам нужно это в styles.xml слишком – Booger

ответ

0

Кроме того, необходимо следующее в вашей базе res\values\styles.xml

<!-- Main Theme --> 
    <style name="MainTheme" parent="Theme.AppCompat.Light.NoActionBar" 
... 
> 
+0

Если я добавлю новый файл 'styles.xml' под 'res', я получаю ошибку при создании. Msgstr "Недействительный каталог ресурсов". В настоящее время я работаю в AIDE вместо Studio .. это будет иметь значение? – Esby

+0

FWIW (или следующий парень) это мы в подклассе «values», я изменил свой ответ, чтобы отразить это. – Booger

0

Нашел ! Итак, в какой-то момент при создании моего приложения появилась новая папка: «res/values-v21/stles.xml» Я не знал, что это произошло, поэтому приложите аргументы, если мое сообщение вводит в заблуждение, не перечисляя это. В нем снова была определена «AppTheme», которая отменяет определение, которое я создал в res/values ​​/ styles.xml.

С тех пор гугл и нашел документацию по этому вопросу .. https://developer.android.com/training/material/compatibility.html#Theme

Благодаря спросить, кто внес предложения, надеюсь, что я не тратить свое время. Может быть, будет какой-то другой нуб, который найдет это полезным!

+0

Это действительная папка, и вы должны поместить информацию стилей, относящуюся к v21. Это неверно, и ваше приложение будет работать нормально, если оно будет установлено на устройство v21 +. Ваша первоначальная проблема заключалась в том, что вам не хватало этот файл изначально (в любой папке). – Booger

Смежные вопросы