я хочу создать собственную панель инструментов, но когда я открываю свое приложение, мое приложение вылетает - PullRequest
0 голосов
/ 16 ноября 2018

это мой XML-файл панели инструментов

<?xml version="1.0" encoding="utf-8"?>
   <android.support.v7.widget.Toolbarxmlns:android="http://schemas.android.com /apk/res/android"    
android:layout_width="match_parent"
android:layout_height="wrap_content"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:background="#affa0505"
android:elevation="4sp"
android:theme="@style/Base.ThemeOverlay.AppCompat.Dark.ActionBar"
app:popupTheme="@style/Base.ThemeOverlay.AppCompat.Light"
app:titleTextColor="#fff"
>

, и я добавил этот файл в mainActivity

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

и это мой файл меню

<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"
 tools:context="com.example.shery.youtubevideodownloader.Main2Activity">
 <item
    android:id="@+id/action_settings"
    android:orderInCategory="100"
    android:icon="@drawable/share"
    app:showAsAction="ifRoom"
    android:title="@string/action_settings" />
</menu>

и это мой java-файл

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


    @Override
public boolean onCreateOptionsMenu(Menu menu) {
    MenuInflater inflater = getMenuInflater();
    inflater.inflate(R.menu.menu_main2, menu);
    return true;
}

и ошибка

E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.shery.youtubevideodownloader, PID: 25483
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.shery.youtubevideodownloader/com.example.shery.youtubevideodownloader.SplashScreen}: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.support.v7.app.ActionBar.hide()' on a null object reference
    at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2957)
    at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3032)
    at android.app.ActivityThread.-wrap11(Unknown Source:0)
    at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1696)
    at android.os.Handler.dispatchMessage(Handler.java:105)
    at android.os.Looper.loop(Looper.java:164)
    at android.app.ActivityThread.main(ActivityThread.java:6944)
    at java.lang.reflect.Method.invoke(Native Method)
    at com.android.internal.os.Zygote$MethodAndArgsCaller.run(Zygote.java:327)
    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1374)
 Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.support.v7.app.ActionBar.hide()' on a null object reference
    at com.example.shery.youtubevideodownloader.SplashScreen.onCreate(SplashScreen.java:17)
    at android.app.Activity.performCreate(Activity.java:7183)
    at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1220)
    at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2910)
    at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3032) 
    at android.app.ActivityThread.-wrap11(Unknown Source:0) 
    at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1696) 
    at android.os.Handler.dispatchMessage(Handler.java:105) 
    at android.os.Looper.loop(Looper.java:164) 
    at android.app.ActivityThread.main(ActivityThread.java:6944) 
    at java.lang.reflect.Method.invoke(Native Method) 
    at     com.android.internal.os.Zygote$MethodAndArgsCaller.run(Zygote.java:327) 
    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1374) 

I / Ads: Измерение приложения запускается, версия: 13001

Я не знаю, в чем заключается ошибка в моем проекте, когда я открываю свое приложение, мое приложение вылетает, и я хочу добавить панель инструментов

, и это мой код spalshScreen

package com.example.shery.youtubevideodownloader;

import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.ProgressBar;

public class SplashScreen extends AppCompatActivity {

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    requestWindowFeature(Window.FEATURE_NO_TITLE);
    getSupportActionBar().hide();
      this.getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREENWindowManager.LayoutParams.FLAG_FULLSCREEN);,   
    setContentView(R.layout.activity_splash_screen);





    Thread th = new Thread(){
        @Override
        public void run() {
            super.run();

            try {
                //You Can Increase Or Decrease The Timing Of Splash Screen By Adding the number on sleep.
                sleep(2000);
                Intent intent = new Intent(SplashScreen.this,MainActivity.class);
                startActivity(intent);

                finish();

            }catch (Exception e){
                e.printStackTrace();
            }
        }
    };
    th.start();


}

}

Ответы [ 3 ]

0 голосов
/ 16 ноября 2018
public class SplashScreen extends AppCompatActivity {

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    requestWindowFeature(Window.FEATURE_NO_TITLE);
    this.getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREENWindowManager.LayoutParams.FLAG_FULLSCREEN);,   
    setContentView(R.layout.activity_splash_screen);

    new Handler().postDelayed(new Runnable() {
            @Override
            public void run() {
                 try {
                Intent intent = new Intent(SplashScreen.this,MainActivity.class);
                startActivity(intent);
                finish();

            }catch (Exception e){
                e.printStackTrace();
            }
            }
        },2000);
}

}
0 голосов
/ 16 ноября 2018

Прежде всего, если вы хотите скрыть панель инструментов, то почему вы добавляете панель инструментов в свой xml?

В любом случае, чтобы все заработало, сделайте следующее:

  1. В вашем toolbar.xml поместите пробел между панелью инструментов и xmlns.

  2. Добавьте идентификатор к вашему android.support.v7.widget.Toolbar в toolbar.xml

<android.support.v7.widget.Toolbar xmlns:android="http://schemas.android.com /apk/res/android"    
android:id="@+id/toolbar"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:background="#affa0505"
    android:elevation="4sp"
    android:theme="@style/Base.ThemeOverlay.AppCompat.Dark.ActionBar"
    app:popupTheme="@style/Base.ThemeOverlay.AppCompat.Light"
    app:titleTextColor="#fff"
    >
  1. Удалить android:id="@+id/toolbar" из тега включения.
  2. Измените код SplashScreen, вам нужно вызвать метод setSupportActionBar, прежде чем скрывать панель инструментов:
     requestWindowFeature(Window.FEATURE_NO_TITLE);

          this.getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREENWindowManager.LayoutParams.FLAG_FULLSCREEN);,

        setContentView(R.layout.activity_splash_screen);
setSupportActionBar(toolbar);
getSupportActionBar().hide();
0 голосов
/ 16 ноября 2018

В onCreate() звоните

getSupportActionBar().hide();

почему?Убери это.У вас не должно быть значения по умолчанию ActionBar, так как вы хотите панель инструментов ..Если ваша тема в styles.xml похожа на

<style name="AppTheme" parent="Theme.AppCompat.Light.DarkActionBar">

, измените ее на:

<style name="AppTheme" parent="Theme.AppCompat.Light.NoActionBar">
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...