Setsupportactionbar toolbar ошибка

I’ve been looking for an answer and I’ve tried many possible solutions, but nothing seems to work..

I’m trying to setup a Material Action Bar following this tutorial.

Here’s my code:

tool_bar.xml:

<?xml version="1.0" encoding="utf-8"?>
<android.support.v7.widget.Toolbar xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:background="@color/ColorPrimary"
    android:elevation="4dp">

</android.support.v7.widget.Toolbar>

activity.xml:

<?xml version="1.0" encoding="utf-8"?>
<android.support.v4.widget.DrawerLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/drawer_layout"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="#FFFFFF">
    <!-- The main content view -->
    <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:orientation="vertical">

        <include
            android:id="@+id/app_bar"
            layout="@layout/tool_bar" />
    </RelativeLayout>
    <!-- Navigation Drawer -->
    <ListView
        android:id="@+id/left_drawer"
        android:layout_width="220dp"
        android:layout_height="match_parent"
        android:layout_gravity="left"
        android:background="#1C1C1C"
        android:divider="@android:color/darker_gray"
        android:dividerHeight="1dp" />

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

And finally my activity.java:

import android.app.ActionBar;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.Toolbar;


public class rutaActivity extends ActionBarActivity {

private Toolbar toolbar;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_ruta);

        getSupportActionBar().hide();//Ocultar ActivityBar anterior

        toolbar = (Toolbar) findViewById(R.id.app_bar);
        setSupportActionBar(toolbar); //HERE'S THE PROBLEM !!!!

Error:

setSupporActionBar (android.support.v7.widget.Toolbar) in ActionBarActivity cannot be applied to (android.widget.Toolbar)

How can I fix this?

Ssnake707

8 / 8 / 11

Регистрация: 02.02.2015

Сообщений: 140

1

16.12.2015, 23:25. Показов 6279. Ответов 2

Метки toolbar (Все метки)


Студворк — интернет-сервис помощи студентам

Всем привет.
Ломаю голову уже несколько часов, не могу понять почему вылетает приложение на setSupportActionBar(toolBar);

Код MainActivity.java

Кликните здесь для просмотра всего текста

Java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
package com.ssnake.highday;
 
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.Menu;
import android.view.MenuItem;
 
 
public class MainActivity extends AppCompatActivity {
 
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        Toolbar toolbar = (Toolbar) findViewById(R.id.main_toolbar);
        initToolBar(toolbar);
    }
 
    private void initToolBar(Toolbar toolbar) {
        toolbar.inflateMenu(R.menu.menu_main);
        toolbar.setTitle(getResources().getString(R.string.app_name));
        setSupportActionBar(toolbar);
    }
 
    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.menu_main, menu);
        return true;
    }
 
    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();
 
        //noinspection SimplifiableIfStatement
 
 
        return true;
    }
}

Код main.xml

Кликните здесь для просмотра всего текста

XML
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    tools:context=".MainActivity">
 
    <android.support.v7.widget.Toolbar
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:minHeight="?attr/actionBarSize"
        android:background="@color/blue"
        android:id="@+id/main_toolbar"
        android:theme="@android:style/Theme.Holo.NoActionBar"
        app:popupTheme="@style/ThemeOverlay.AppCompat.Light">
    </android.support.v7.widget.Toolbar>
 
</LinearLayout>

Код menu_main.xml

Кликните здесь для просмотра всего текста

XML
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    xmlns:appcompat="http://schemas.android.com/apk/res-auto"
    tools:context=".MainActivity">
    <item
        android:id="@+id/menu_search"
        android:title="@string/search"
        android:theme="@android:style/Theme.Holo.Light.NoActionBar"
        appcompat:actionViewClass="android.support.v7.widget.SearchView"
        appcompat:showAsAction="always" />
    <item
        android:id="@+id/menu_filter"
        android:title="@string/filtr"
        app:showAsAction="never" />
    <item
        android:id="@+id/menu_lang"
        android:title="@string/lang"
        app:showAsAction="never" />
    <item
        android:id="@+id/menu_uvedomlenie"
        android:title="@string/uvedomlenie"
        app:showAsAction="never" />
    <item
        android:id="@+id/menu_addMyPrazdnik"
        android:title="@string/addMyPrazdnik"
        app:showAsAction="never" />
    <item
        android:id="@+id/menu_myStrana"
        android:title="@string/MyStrana"
        app:showAsAction="never" />
 
</menu>

Логи

Кликните здесь для просмотра всего текста

12-17 02:20:55.471 32073-32073/com.ssnake.highday W/dalvikvm﹕ VFY: unable to find class referenced in signature (Landroid/view/SearchEvent
12-17 02:20:55.471 32073-32073/com.ssnake.highday I/dalvikvm﹕ Could not find method android.view.Window$Callback.onSearchRequested, referenced from method android.support.v7.internal.view.WindowCallbackWrapper.onSearchRequested
12-17 02:20:55.471 32073-32073/com.ssnake.highday W/dalvikvm﹕ VFY: unable to resolve interface method 14478: Landroid/view/Window$Callback;.onSearchRequested (Landroid/view/SearchEventZ
12-17 02:20:55.471 32073-32073/com.ssnake.highday D/dalvikvm﹕ VFY: replacing opcode 0x72 at 0x0002
12-17 02:20:55.471 32073-32073/com.ssnake.highday I/dalvikvm﹕ Could not find method android.view.Window$Callback.onWindowStartingActionMode, referenced from method android.support.v7.internal.view.WindowCallbackWrapper.onWindowStartingActionMod e
12-17 02:20:55.471 32073-32073/com.ssnake.highday W/dalvikvm﹕ VFY: unable to resolve interface method 14482: Landroid/view/Window$Callback;.onWindowStartingActionMode (Landroid/view/ActionMode$Callback;I)Landroid/view/ActionMode;
12-17 02:20:55.471 32073-32073/com.ssnake.highday D/dalvikvm﹕ VFY: replacing opcode 0x72 at 0x0002
12-17 02:20:55.521 32073-32073/com.ssnake.highday I/dalvikvm﹕ Could not find method android.content.res.TypedArray.getChangingConfigurations, referenced from method android.support.v7.internal.widget.TintTypedArray.getChangingConfigurations
12-17 02:20:55.521 32073-32073/com.ssnake.highday W/dalvikvm﹕ VFY: unable to resolve virtual method 406: Landroid/content/res/TypedArray;.getChangingConfigurations ()I
12-17 02:20:55.521 32073-32073/com.ssnake.highday D/dalvikvm﹕ VFY: replacing opcode 0x6e at 0x0002
12-17 02:20:55.521 32073-32073/com.ssnake.highday I/dalvikvm﹕ Could not find method android.content.res.TypedArray.getType, referenced from method android.support.v7.internal.widget.TintTypedArray.getType
12-17 02:20:55.521 32073-32073/com.ssnake.highday W/dalvikvm﹕ VFY: unable to resolve virtual method 428: Landroid/content/res/TypedArray;.getType (I)I
12-17 02:20:55.521 32073-32073/com.ssnake.highday D/dalvikvm﹕ VFY: replacing opcode 0x6e at 0x0002
12-17 02:20:55.631 32073-32073/com.ssnake.highday I/dalvikvm﹕ Could not find method android.content.res.Resources.getDrawable, referenced from method android.support.v7.internal.widget.ResourcesWrapper.getDrawable
12-17 02:20:55.631 32073-32073/com.ssnake.highday W/dalvikvm﹕ VFY: unable to resolve virtual method 369: Landroid/content/res/Resources;.getDrawable (ILandroid/content/res/Resources$ThemeLandroid/graphics/drawable/Drawable;
12-17 02:20:55.631 32073-32073/com.ssnake.highday D/dalvikvm﹕ VFY: replacing opcode 0x6e at 0x0002
12-17 02:20:55.631 32073-32073/com.ssnake.highday I/dalvikvm﹕ Could not find method android.content.res.Resources.getDrawableForDensity, referenced from method android.support.v7.internal.widget.ResourcesWrapper.getDrawableForDensity
12-17 02:20:55.631 32073-32073/com.ssnake.highday W/dalvikvm﹕ VFY: unable to resolve virtual method 371: Landroid/content/res/Resources;.getDrawableForDensity (IILandroid/content/res/Resources$ThemeLandroid/graphics/drawable/Drawable;
12-17 02:20:55.631 32073-32073/com.ssnake.highday D/dalvikvm﹕ VFY: replacing opcode 0x6e at 0x0002
12-17 02:20:55.681 32073-32073/com.ssnake.highday D/AndroidRuntime﹕ Shutting down VM
12-17 02:20:55.681 32073-32073/com.ssnake.highday W/dalvikvm﹕ threadid=1: thread exiting with uncaught exception (group=0x41ae7da0)
12-17 02:20:55.681 32073-32073/com.ssnake.highday E/AndroidRuntime﹕ FATAL EXCEPTION: main
Process: com.ssnake.highday, PID: 32073
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.ssnake.highday/com.ssnake.highday.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:2449)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2509)
at android.app.ActivityThread.access$900(ActivityThread.java:172)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1308)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:146)
at android.app.ActivityThread.main(ActivityThread.java:5694)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:515)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1291)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1107)
at dalvik.system.NativeStart.main(Native Method)
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 android.support.v7.app.AppCompatDelegateImplV7.setSupportActionBar(AppCompatDele gateImplV7.java:199)
at android.support.v7.app.AppCompatActivity.setSupportActionBar(AppCompatActivity.j ava:99)
at com.ssnake.highday.MainActivity.initToolBar(MainActivity.java:23)
at com.ssnake.highday.MainActivity.onCreate(MainActivity.java:17)
at android.app.Activity.performCreate(Activity.java:5541)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1093)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2413)
************at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2509)
************at android.app.ActivityThread.access$900(ActivityThread.java:172)
************at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1308)
************at android.os.Handler.dispatchMessage(Handler.java:102)
************at android.os.Looper.loop(Looper.java:146)
************at android.app.ActivityThread.main(ActivityThread.java:5694)
************at java.lang.reflect.Method.invokeNative(Native Method)
************at java.lang.reflect.Method.invoke(Method.java:515)
************at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1291)
************at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1107)
************at dalvik.system.NativeStart.main(Native Method)

12-17 02:20:58.071 32073-32073/com.ssnake.highday I/Process﹕ Sending signal. PID: 32073 SIG: 9



0



Programming

Эксперт

94731 / 64177 / 26122

Регистрация: 12.04.2006

Сообщений: 116,782

16.12.2015, 23:25

Ответы с готовыми решениями:

Ошибка с Toolbar
Помогите пожалуйста. Программа вылетает из-за 2 и 3 строчки, с чем это связано?
TabLayout…

Ошибка при смене toolbar
Имеется тулбар
&lt;android.support.v7.widget.Toolbar…

Toolbar
Не получается отобразить .png картинку в toolbar. там в toolbar квадратное место выдсется для…

ToolBar
Драсти, какое свойство в ToolBar нужно поменять, чтобы можно было в любом месте разместить…

2

Mikalai

266 / 242 / 96

Регистрация: 11.01.2015

Сообщений: 673

17.12.2015, 01:13

2

Лучший ответ Сообщение было отмечено Ssnake707 как решение

Решение

Ssnake707, в файле styles.xml замени тему от которой наследуется твоя тема. Например так:

XML
1
<style name="AppTheme" parent="Theme.AppCompat.Light.NoActionBar">



1



8 / 8 / 11

Регистрация: 02.02.2015

Сообщений: 140

17.12.2015, 01:15

 [ТС]

3

Mikalai, Вот я глупец, спасибо тебе большое, ты не представляешь как ты мне помог



0



IT_Exp

Эксперт

87844 / 49110 / 22898

Регистрация: 17.06.2006

Сообщений: 92,604

17.12.2015, 01:15

Помогаю со студенческими работами здесь

ToolBar
Доброго времени суток! Возникла проблема с отображением картинок на кнопках в панели инструментов….

Toolbar
Есть мысль подсадить свою целевую аудиторию на тулбар и заставить людей больше посещать свой сайт….

Toolbar
объясните мне пожалуйста как работает компонент ToolBar и где мне его найти. Написано в задании…

ToolBar
Здравствуйте
Как можно присвоить иконку к кнопке ToolBar через TImageList(il1) ?

Искать еще темы с ответами

Или воспользуйтесь поиском по форуму:

3

In Android development, using the ToolBar control instead of the ActionBar control, you need to use the setSupportActionBar() method in the java code, as follows:

1 Toolbar toolbar = (Toolbar) this.findViewById(R.id.toolBar);
2 this.setSupportActionBar(toolbar);

There are two common types of errors:

1. Method parameter error

This kind of error is caused by the wrong class, put the following code

1 import android.widget.Toolbar;

Replace with the following code

1 import android.support.v7.widget.Toolbar;

2. Method name error

Need inheritanceActionBarActivity classorAppCompatActivity class

== Because the ActionBarActivity class is out of date, it is recommended to inherit the AppCompatActivity class. ==

Note: If you inherit the AppCompatActivity class, you need to use the Theme.AppCompat.Light.NoActionBar theme, a chestnut

1 <style name="AppTheme.Base" parent="Theme.AppCompat.Light.NoActionBar">
2         <item name="android:windowNoTitle">true</item>
3         <item name="android:windowActionBar">false</item>
4 </style>

I’ve been looking for an answer and I’ve tried many possible solutions, but nothing seems to work..

I’m trying to setup a Material Action Bar following this tutorial.

Here’s my code:

tool_bar.xml:

<?xml version="1.0" encoding="utf-8"?>
<android.support.v7.widget.Toolbar xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:background="@color/ColorPrimary"
    android:elevation="4dp">

</android.support.v7.widget.Toolbar>

activity.xml:

<?xml version="1.0" encoding="utf-8"?>
<android.support.v4.widget.DrawerLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/drawer_layout"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="#FFFFFF">
    <!-- The main content view -->
    <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:orientation="vertical">

        <include
            android:id="@+id/app_bar"
            layout="@layout/tool_bar" />
    </RelativeLayout>
    <!-- Navigation Drawer -->
    <ListView
        android:id="@+id/left_drawer"
        android:layout_width="220dp"
        android:layout_height="match_parent"
        android:layout_gravity="left"
        android:background="#1C1C1C"
        android:divider="@android:color/darker_gray"
        android:dividerHeight="1dp" />

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

And finally my activity.java:

import android.app.ActionBar;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.Toolbar;


public class rutaActivity extends ActionBarActivity {

private Toolbar toolbar;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_ruta);

        getSupportActionBar().hide();//Ocultar ActivityBar anterior

        toolbar = (Toolbar) findViewById(R.id.app_bar);
        setSupportActionBar(toolbar); //HERE'S THE PROBLEM !!!!

Error:

setSupporActionBar (android.support.v7.widget.Toolbar) in ActionBarActivity cannot be applied to (android.widget.Toolbar)

How can I fix this?

This question is related to
android
android-actionbar
material-design
toolbar

In your Activity.java import android.support.v7.widget.Toolbar instead of android.widget.Toolbar:

import android.app.ActionBar;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.support.v7.widget.Toolbar;


public class rutaActivity extends AppCompactActivity {

private Toolbar toolbar;
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_ruta);

    getSupportActionBar().hide();//Ocultar ActivityBar anterior

    toolbar = (Toolbar) findViewById(R.id.app_bar);
    setSupportActionBar(toolbar); //NO PROBLEM !!!!

Update:

If you are using androidx, replace

import android.support.v7.widget.Toolbar;
import android.support.v7.app.AppCompatActivity;

with newer imports

import androidx.appcompat.widget.Toolbar;
import androidx.appcompat.app.AppCompatActivity;

In Android development, to use the ToolBar control to replace the ActionBar control, you need to use the setSupportActionBar() method in the java code, as follows:

1 Toolbar toolbar = (Toolbar) this.findViewById(R.id.toolBar);
2 this.setSupportActionBar(toolbar);

There are two common types of errors:

1. Method parameter error


This kind of error is because the wrong class is imported, put the following code

1 import android.widget.Toolbar;

Replace with the following code

1 import android.support.v7.widget.Toolbar;

2. Method name error

Need to inherit ActionBarActivity class or AppCompatActivity class.

Because the ActionBarActivity class is obsolete, it is recommended to inherit the AppCompatActivity class.

Note: If you inherit the AppCompatActivity class, you need to use the Theme.AppCompat.Light.NoActionBar theme, for example

<style name="AppTheme.Base" parent="Theme.AppCompat.Light.NoActionBar">
        <item name="android:windowNoTitle">true</item>
        <item name="android:windowActionBar">false</item>
</style>

Similar Posts:

Понравилась статья? Поделить с друзьями:
  • Sql откат транзакции при ошибке
  • Setracker2 ошибка сети
  • Spore 1001 ошибка
  • Setracker2 ошибка привязки неверный регистрационный номер
  • Spn 791 fmi 5 ошибка kamaz