工具栏后退按钮错误Android [英] toolbar back button error Android

查看:102
本文介绍了工具栏后退按钮错误Android的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在我创建的工具栏中添加一个后退"按钮,因为我删除了默认按钮以使某些选项卡具有材质设计效果,但是每次添加代码使该按钮出现时,Android都会给出一个异常提示这个:

E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.juan.sdfnsdfnskdfnskdfmsfd, PID: 13348
java.lang.NullPointerException: Attempt to invoke virtual method 'int android.support.v4.widget.DrawerLayout.getDrawerLockMode(int)' on a null object reference
at android.support.v7.app.ActionBarDrawerToggle.toggle(ActionBarDrawerToggle.java:284)
at android.support.v7.app.ActionBarDrawerToggle$1.onClick(ActionBarDrawerToggle.java:202)
at android.view.View.performClick(View.java:6308)
at android.view.View$PerformClick.run(View.java:23969)
at android.os.Handler.handleCallback(Handler.java:751)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:154)
at android.app.ActivityThread.main(ActivityThread.java:6823)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1557)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1445)

如果我只在自己创建的工具栏中编写相应的代码,我将无法理解使用空对象引用的含义.

这是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:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="@color/toolbar_morado"
android:id="@+id/toolbar_lista_compras"
android:minHeight="?attr/actionBarSize">

<RelativeLayout
android:layout_width="match_parent"
android:layout_height="wrap_content">

<TextView
    android:id="@+id/contador_toolbar"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="Lista de compras"
    android:textSize="18sp"
    android:textColor="#ffffff"/>

</RelativeLayout>

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

这是我实现工具栏的地方:

<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.design.widget.AppBarLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:theme="@style/ThemeOverlay.AppCompat.Dark.ActionBar"
        android:id="@+id/appBarLayoutCalcular">

        <include layout="@layout/toolbar"></include>

        <android.support.design.widget.TabLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:id="@+id/tablayoutCalcular"
            app:tabGravity="fill"
            app:tabMode="fixed"
            android:background="@color/toolbar_anaranjado"
            app:tabTextAppearance="@style/myTabSize"
            app:tabIndicatorColor="#5c1be1"/>

    </android.support.design.widget.AppBarLayout>

    <android.support.v4.view.ViewPager
        android:id="@+id/viewPagerCalcular"
        android:layout_width="match_parent"
        android:layout_height="match_parent" />

</LinearLayout>

这是我的课程:

public class CalculateMaterials extends AppCompatActivity{

DrawerLayout drawerLayout;
ActionBarDrawerToggle actionBarDrawerToggle;
Toolbar toolbar;
NavigationView navigationView;
TabLayout tabLayout;
ViewPager viewPager;
ViewPagerAdapter viewPagerAdapter;
String tabSeleccionado;

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

    toolbar = (Toolbar)findViewById(R.id.toolbar_shopping_list);
    toolbar.setBackgroundColor(ContextCompat.getColor(getApplicationContext(), R.color.toolbar_anaranjado));
    setSupportActionBar(toolbar);

    // text for the toolbar
    TextView textoToolbar = (TextView)findViewById(R.id.contador_toolbar);
    textoToolbar.setText("Calcular los materiales");

    // status bar color
    if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {

        getWindow().setStatusBarColor(ContextCompat.getColor(getApplicationContext(), R.color.statusBar_anaranjado));

    }


    // adding toolbar back button
    // this is where I have the error 
    if (toolbar != null) {
        toolbar.setNavigationIcon(R.drawable.backButton);
        toolbar.setNavigationOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                onBackPressed();
            }
        });
    }

    drawerLayout = (DrawerLayout)findViewById(R.id.drawer_layout);

    actionBarDrawerToggle = new ActionBarDrawerToggle(this, drawerLayout, toolbar, R.string.drawer_open, R.string.drawer_close);

    navigationView = (NavigationView)findViewById(R.id.navigationView);

    tabLayout = (TabLayout)findViewById(R.id.tablayoutCalcular);

    viewPager = (ViewPager)findViewById(R.id.viewPagerCalcular);

    // adding the tabs
    viewPagerAdapter = new ViewPagerAdapter(getSupportFragmentManager());
    viewPagerAdapter.addFragments(new FragmentCalcular(), "Con area");
    viewPagerAdapter.addFragments(new FragmentCalcular2(), "Con metros");

    viewPager.setAdapter(viewPagerAdapter);

    tabLayout.setupWithViewPager(viewPager);

我也尝试:

// add back arrow to toolbar
if (getSupportActionBar() != null){
    getSupportActionBar().setDisplayHomeAsUpEnabled(true);
    getSupportActionBar().setDisplayShowHomeEnabled(true);
}

这也会产生相同的错误.

那么,有人可以帮助我解决这个问题吗?

修改

感谢所有尝试帮助我解决此问题的人.我终于找到了错误.

前一段时间,我试图在所有活动中添加一个NavigationView,但是我忘记删除该类中的必要代码,这就是为什么抽屉布局不出现在xml中的原因.

因此,当我删除抽屉布局变量时,一切正常!

解决方案

尝试一下

    toolbar = (Toolbar) findViewById(R.id.toolbar);
    setSupportActionBar(toolbar);

    getSupportActionBar().setDisplayHomeAsUpEnabled(true);
    toolbar.setNavigationOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            onBackPressed();
        }
    });

I want to add a Back button in a toolbar that I created because I deleted the default one to have the material design effect with some tabs, but every time I add the code to make that button appear, Android gives an exception saying this:

E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.juan.sdfnsdfnskdfnskdfmsfd, PID: 13348
java.lang.NullPointerException: Attempt to invoke virtual method 'int android.support.v4.widget.DrawerLayout.getDrawerLockMode(int)' on a null object reference
at android.support.v7.app.ActionBarDrawerToggle.toggle(ActionBarDrawerToggle.java:284)
at android.support.v7.app.ActionBarDrawerToggle$1.onClick(ActionBarDrawerToggle.java:202)
at android.view.View.performClick(View.java:6308)
at android.view.View$PerformClick.run(View.java:23969)
at android.os.Handler.handleCallback(Handler.java:751)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:154)
at android.app.ActivityThread.main(ActivityThread.java:6823)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1557)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1445)

I do not understand what it means with a null object reference if I only write the corresponding code in the toolbar that I created.

This is the 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:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="@color/toolbar_morado"
android:id="@+id/toolbar_lista_compras"
android:minHeight="?attr/actionBarSize">

<RelativeLayout
android:layout_width="match_parent"
android:layout_height="wrap_content">

<TextView
    android:id="@+id/contador_toolbar"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="Lista de compras"
    android:textSize="18sp"
    android:textColor="#ffffff"/>

</RelativeLayout>

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

This is where I implement the toolbar:

<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.design.widget.AppBarLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:theme="@style/ThemeOverlay.AppCompat.Dark.ActionBar"
        android:id="@+id/appBarLayoutCalcular">

        <include layout="@layout/toolbar"></include>

        <android.support.design.widget.TabLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:id="@+id/tablayoutCalcular"
            app:tabGravity="fill"
            app:tabMode="fixed"
            android:background="@color/toolbar_anaranjado"
            app:tabTextAppearance="@style/myTabSize"
            app:tabIndicatorColor="#5c1be1"/>

    </android.support.design.widget.AppBarLayout>

    <android.support.v4.view.ViewPager
        android:id="@+id/viewPagerCalcular"
        android:layout_width="match_parent"
        android:layout_height="match_parent" />

</LinearLayout>

This is my class:

public class CalculateMaterials extends AppCompatActivity{

DrawerLayout drawerLayout;
ActionBarDrawerToggle actionBarDrawerToggle;
Toolbar toolbar;
NavigationView navigationView;
TabLayout tabLayout;
ViewPager viewPager;
ViewPagerAdapter viewPagerAdapter;
String tabSeleccionado;

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

    toolbar = (Toolbar)findViewById(R.id.toolbar_shopping_list);
    toolbar.setBackgroundColor(ContextCompat.getColor(getApplicationContext(), R.color.toolbar_anaranjado));
    setSupportActionBar(toolbar);

    // text for the toolbar
    TextView textoToolbar = (TextView)findViewById(R.id.contador_toolbar);
    textoToolbar.setText("Calcular los materiales");

    // status bar color
    if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {

        getWindow().setStatusBarColor(ContextCompat.getColor(getApplicationContext(), R.color.statusBar_anaranjado));

    }


    // adding toolbar back button
    // this is where I have the error 
    if (toolbar != null) {
        toolbar.setNavigationIcon(R.drawable.backButton);
        toolbar.setNavigationOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                onBackPressed();
            }
        });
    }

    drawerLayout = (DrawerLayout)findViewById(R.id.drawer_layout);

    actionBarDrawerToggle = new ActionBarDrawerToggle(this, drawerLayout, toolbar, R.string.drawer_open, R.string.drawer_close);

    navigationView = (NavigationView)findViewById(R.id.navigationView);

    tabLayout = (TabLayout)findViewById(R.id.tablayoutCalcular);

    viewPager = (ViewPager)findViewById(R.id.viewPagerCalcular);

    // adding the tabs
    viewPagerAdapter = new ViewPagerAdapter(getSupportFragmentManager());
    viewPagerAdapter.addFragments(new FragmentCalcular(), "Con area");
    viewPagerAdapter.addFragments(new FragmentCalcular2(), "Con metros");

    viewPager.setAdapter(viewPagerAdapter);

    tabLayout.setupWithViewPager(viewPager);

I also try with:

// add back arrow to toolbar
if (getSupportActionBar() != null){
    getSupportActionBar().setDisplayHomeAsUpEnabled(true);
    getSupportActionBar().setDisplayShowHomeEnabled(true);
}

That also gives the same error.

So, Can anyone help me with this problem?

Edit

Thanks to everyone who tried to help me with this problem. I finally found the error.

Some time ago, I tried to add a navigationView in all the activities, but I forgot to delete the necessary code in the class, that's why the drawerLayout doesnt appears in the xml.

So, when I delete the drawerLayout variable, everything works!

解决方案

Try this

    toolbar = (Toolbar) findViewById(R.id.toolbar);
    setSupportActionBar(toolbar);

    getSupportActionBar().setDisplayHomeAsUpEnabled(true);
    toolbar.setNavigationOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            onBackPressed();
        }
    });

这篇关于工具栏后退按钮错误Android的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆