Android:在包含工具栏后应用程序崩溃

huangapple go评论81阅读模式
英文:

Android : App Crash After Included Toolbar

问题

以下是您提供的内容的翻译:

首次在Android中创建工具栏

styles.xml

<resources>
    <!-- 应用程序的基本主题。 -->
    <style name="AppTheme" parent="Theme.MaterialComponents.Light.DarkActionBar">
        <!-- 在此处自定义您的主题。 -->
        <item name="colorPrimary">@color/colorPrimary</item>
        <item name="colorPrimaryDark">@color/colorPrimaryDark</item>
        <item name="colorAccent">@color/colorAccent</item>
    </style>
</resources>

在将其更改为NoActionBar后,它显示错误android.widget.LinearLayout无法转换为androidx.appcompat.widget.Toolbar,即使将其更改为RelativeLayout也会出现相同的错误。

首先,我创建一个新的XML布局用于工具栏,根元素是Toolbar,在XML布局中,我无法创建<Toolbar>选项,因为它显示错误:

“View需要API级别21(当前最小为16):”为此我尝试添加android.support.v7.widget...它也显示错误,然后我尝试迁移到AndroidX。

然后,我使用新的XML文件创建了我的工具栏,根元素为RelativeLayout。

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    xmlns:app="http://schemas.android.com/apk/res-auto">
    <androidx.appcompat.widget.Toolbar
        android:id="@+id/toolbar"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:minHeight="?attr/actionBarSize"
        app:titleTextColor="@android:color/white"
        android:background="?attr/colorPrimary"
        />
</RelativeLayout>

然后,我将工具栏包含在activity_main.xml中。

<include
        android:id="@+id/toolbar"
        layout="@layout/toolbar"
        />

然后,我在Activity.java中声明了它。

package com.Karth.check;

import androidx.appcompat.app.AppCompatActivity;

import android.os.Bundle;
import androidx.appcompat.widget.Toolbar;

public class MainActivity extends AppCompatActivity {

    Toolbar mToolbar;

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

       mToolbar=findViewById(R.id.toolbar);
        setSupportActionBar(mToolbar);
    }
}

我运行我的应用程序以检查是否已添加,但我的应用程序崩溃并显示错误。

2020-08-04 17:50:17.973 18038-18038/com.Karth.check E/AndroidRuntime: FATAL EXCEPTION: main
    Process: com.Karth.checkslate, PID: 18038
    java.lang.RuntimeException: Unable to start activity ComponentInfo{com.Karth.check/com.Karth.check.MainActivity}: java.lang.IllegalStateException: This Activity already has an action bar supplied by the window decor. Do not request Window.FEATURE_SUPPORT_ACTION_BAR and set windowActionBar to false in your theme to use a Toolbar instead.
        at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2913)
        at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3048)
        at android.app.servertransaction.LaunchActivityItem.execute(LaunchActivityItem.java:78)
        at android.app.servertransaction.TransactionExecutor.executeCallbacks(TransactionExecutor.java:108)
        at android.app.servertransaction.TransactionExecutor.execute(TransactionExecutor.java:68)
        at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1808)
        at android.os.Handler.dispatchMessage(Handler.java:106)
        at android.os.Looper.loop(Looper.java:193)
        at android.app.ActivityThread.main(ActivityThread.java:6669)
        at java.lang.reflect.Method.invoke(Native Method)
        at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:493)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:858)
     Caused by: java.lang.IllegalStateException: This Activity already has an action bar supplied by the window decor. Do not request Window.FEATURE_SUPPORT_ACTION_BAR and set windowActionBar to false in your theme to use a Toolbar instead.
        at androidx.appcompat.app.AppCompatDelegateImpl.setSupportActionBar(AppCompatDelegateImpl.java:421)
        at androidx.appcompat.app.AppCompatActivity.setSupportActionBar(AppCompatActivity.java:150)
        at com.Karth.checkslate.MainActivity.onCreate(MainActivity.java:18)
        at android.app.Activity.performCreate(Activity.java:7136)
        at android.app.Activity.performCreate(Activity.java:7127)
        at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1271)
        at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2893)
        at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3048)
        at android.app.servertransaction.LaunchActivityItem.execute(LaunchActivityItem.java:78)
        at android.app.servertransaction.TransactionExecutor.executeCallbacks(TransactionExecutor.java:108)
        at android.app.servertransaction.TransactionExecutor.execute(TransactionExecutor.java:68)
        at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1808)
        at android.os.Handler.dispatchMessage(Handler.java:106)
        at android.os.Looper.loop(Looper.java:193)
        at android.app.ActivityThread.main(ActivityThread.java:6669)
        at java.lang.reflect.Method.invoke(Native Method)
        at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:493)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:858)

Manifest.xml

<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.Karth.check">

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

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

</manifest>

build.gradle

apply plugin: 'com.android.application'

android {
    compileSdkVersion 30
    buildToolsVersion "30.0.1"

    defaultConfig {
        applicationId "com.Karth.check"
        minSdkVersion 16
        targetSdkVersion 30
        versionCode 1
        versionName "1.0"

        testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
    }

    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
        }
    }
}

dependencies {

    implementation 'androidx.appcompat:app

<details>
<summary>英文:</summary>

First Time Creating Toolbar in Android 

styles.xml

    &lt;resources&gt;
        &lt;!-- Base application theme. --&gt;
        &lt;style name=&quot;AppTheme&quot; parent=&quot;Theme.MaterialComponents.Light.DarkActionBar&quot;&gt;
            &lt;!-- Customize your theme here. --&gt;
            &lt;item name=&quot;colorPrimary&quot;&gt;@color/colorPrimary&lt;/item&gt;
            &lt;item name=&quot;colorPrimaryDark&quot;&gt;@color/colorPrimaryDark&lt;/item&gt;
            &lt;item name=&quot;colorAccent&quot;&gt;@color/colorAccent&lt;/item&gt;
        &lt;/style&gt;
    
    &lt;/resources&gt;

It Shows me a Error  `android.widget.LinearLayout cannot be cast to androidx.appcompat.widget.Toolbar `after i change that into  `NoActionBar` even i change that into RelativeLayout then also same Error 


First  I create a New Xml Layout For Toolbar With RootElement as Toolbar inside the Xml Layout i can&#39;t Create a &lt;Toolbar&gt;option Bcoz It Shows the Error 

`&quot; View requires API level 21 (current min is 16): &lt;Toolbar&gt; &quot;` for that i try to add `android.support.v7.widget...` it also Shows The Error and i try to Migrate to AndroidX 

After that i create my Toolbar with new Xml File as RootElement as RelativeLayout 

    &lt;?xml version=&quot;1.0&quot; encoding=&quot;utf-8&quot;?&gt;
    &lt;RelativeLayout xmlns:android=&quot;http://schemas.android.com/apk/res/android&quot;
        android:layout_width=&quot;match_parent&quot;
        android:layout_height=&quot;match_parent&quot;
        xmlns:app=&quot;http://schemas.android.com/apk/res-auto&quot;&gt;
        &lt;androidx.appcompat.widget.Toolbar
            android:id=&quot;@+id/toolbar&quot;
            android:layout_width=&quot;match_parent&quot;
            android:layout_height=&quot;wrap_content&quot;
            android:minHeight=&quot;?attr/actionBarSize&quot;
            app:titleTextColor=&quot;@android:color/white&quot;
            android:background=&quot;?attr/colorPrimary&quot;
            /&gt;
    &lt;/RelativeLayout&gt;

Then i include that Toolbar in activity_main.xml

    &lt;include
            android:id=&quot;@+id/toolbar&quot;
            layout=&quot;@layout/toolbar&quot;
            /&gt;

Then i declare that in Activity.java 

    package com.Karth.check;
    
    import androidx.appcompat.app.AppCompatActivity;
    
    import android.os.Bundle;
    import androidx.appcompat.widget.Toolbar;
    
    public class MainActivity extends AppCompatActivity {
    
        Toolbar mToolbar;
    
        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_main);
    
           mToolbar=findViewById(R.id.toolbar);
            setSupportActionBar(mToolbar);
        }
    }

i run my app to check whether it was added or not..but my app was crashed and Showing error 

    2020-08-04 17:50:17.973 18038-18038/com.Karth.check E/AndroidRuntime: FATAL EXCEPTION: main
        Process: com.Karth.checkslate, PID: 18038
        java.lang.RuntimeException: Unable to start activity ComponentInfo{com.Karth.check/com.Karth.check.MainActivity}: java.lang.IllegalStateException: This Activity already has an action bar supplied by the window decor. Do not request Window.FEATURE_SUPPORT_ACTION_BAR and set windowActionBar to false in your theme to use a Toolbar instead.
            at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2913)
            at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3048)
            at android.app.servertransaction.LaunchActivityItem.execute(LaunchActivityItem.java:78)
            at android.app.servertransaction.TransactionExecutor.executeCallbacks(TransactionExecutor.java:108)
            at android.app.servertransaction.TransactionExecutor.execute(TransactionExecutor.java:68)
            at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1808)
            at android.os.Handler.dispatchMessage(Handler.java:106)
            at android.os.Looper.loop(Looper.java:193)
            at android.app.ActivityThread.main(ActivityThread.java:6669)
            at java.lang.reflect.Method.invoke(Native Method)
            at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:493)
            at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:858)
         Caused by: java.lang.IllegalStateException: This Activity already has an action bar supplied by the window decor. Do not request Window.FEATURE_SUPPORT_ACTION_BAR and set windowActionBar to false in your theme to use a Toolbar instead.
            at androidx.appcompat.app.AppCompatDelegateImpl.setSupportActionBar(AppCompatDelegateImpl.java:421)
            at androidx.appcompat.app.AppCompatActivity.setSupportActionBar(AppCompatActivity.java:150)
            at com.Karth.checkslate.MainActivity.onCreate(MainActivity.java:18)
            at android.app.Activity.performCreate(Activity.java:7136)
            at android.app.Activity.performCreate(Activity.java:7127)
            at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1271)
            at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2893)
            at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3048)&#160;
            at android.app.servertransaction.LaunchActivityItem.execute(LaunchActivityItem.java:78)&#160;
            at android.app.servertransaction.TransactionExecutor.executeCallbacks(TransactionExecutor.java:108)&#160;
            at android.app.servertransaction.TransactionExecutor.execute(TransactionExecutor.java:68)&#160;
            at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1808)&#160;
            at android.os.Handler.dispatchMessage(Handler.java:106)&#160;
            at android.os.Looper.loop(Looper.java:193)&#160;
            at android.app.ActivityThread.main(ActivityThread.java:6669)&#160;
            at java.lang.reflect.Method.invoke(Native Method)&#160;
            at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:493)&#160;
            at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:858)&#160;

Manifest.xml

    &lt;manifest xmlns:android=&quot;http://schemas.android.com/apk/res/android&quot;
        package=&quot;com.Karth.check&quot;&gt;
    
        &lt;application
            android:allowBackup=&quot;true&quot;
            android:icon=&quot;@mipmap/ic_launcher&quot;
            android:label=&quot;@string/app_name&quot;
            android:roundIcon=&quot;@mipmap/ic_launcher_round&quot;
            android:supportsRtl=&quot;true&quot;
            android:theme=&quot;@style/AppTheme&quot;&gt;
            &lt;activity android:name=&quot;.MainActivity&quot;&gt;
                &lt;intent-filter&gt;
                    &lt;action android:name=&quot;android.intent.action.MAIN&quot; /&gt;
    
                    &lt;category android:name=&quot;android.intent.category.LAUNCHER&quot; /&gt;
                &lt;/intent-filter&gt;
            &lt;/activity&gt;
        &lt;/application&gt;
    
    &lt;/manifest&gt;

build.gradle

    apply plugin: &#39;com.android.application&#39;
    
    android {
        compileSdkVersion 30
        buildToolsVersion &quot;30.0.1&quot;
    
        defaultConfig {
            applicationId &quot;com.Karth.check&quot;
            minSdkVersion 16
            targetSdkVersion 30
            versionCode 1
            versionName &quot;1.0&quot;
    
            testInstrumentationRunner &quot;androidx.test.runner.AndroidJUnitRunner&quot;
        }
    
        buildTypes {
            release {
                minifyEnabled false
                proguardFiles getDefaultProguardFile(&#39;proguard-android-optimize.txt&#39;), &#39;proguard-rules.pro&#39;
            }
        }
    }
    
    dependencies {
    
        implementation &#39;androidx.appcompat:appcompat:1.0.0&#39;
        implementation &#39;com.google.android.material:material:1.1.0&#39;
        implementation fileTree(dir: &quot;libs&quot;, include: [&quot;*.jar&quot;])
        implementation &#39;androidx.appcompat:appcompat:1.1.0&#39;
        implementation &#39;androidx.constraintlayout:constraintlayout:1.1.3&#39;
        testImplementation &#39;junit:junit:4.12&#39;
        androidTestImplementation &#39;androidx.test.ext:junit:1.1.1&#39;
        androidTestImplementation &#39;androidx.test.espresso:espresso-core:3.2.0&#39;
    
    
    }

</details>


# 答案1
**得分**: 3

2个问题:

> “此 Activity 已经由窗口装饰提供了操作栏”

将您的应用主题更改为:

```xml
<style name="AppTheme" parent="Theme.MaterialComponents.Light.NoActionBar">

“android.widget.LinearLayout 无法转换为 androidx.appcompat.widget.Toolbar”

在您的布局中,将 include 标签更改为:

<include layout="@layout/toolbar" />
英文:

There are 2 issues:

> This Activity already has an action bar supplied by the window decor

Change your app theme to:

&lt;style name=&quot;AppTheme&quot; parent=&quot;Theme.MaterialComponents.Light.NoActionBar&quot;&gt;

> android.widget.LinearLayout cannot be cast to androidx.appcompat.widget.Toolbar

Change in your layout the include tag to:

&lt;include layout=&quot;@layout/toolbar&quot; /&gt;

答案2

得分: 1