【问题标题】:Trouble with styles风格问题
【发布时间】:2017-07-22 16:26:48
【问题描述】:

我有一个包含两个活动的应用程序。第一个Activity 使用Toolbar,但第二个Activity 应该使用ActionBar。当我从第一个调用第二个Activity 时,应用程序就会起飞。有什么问题?

清单:

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
      package="com.example.nikva.easyreading">

<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
<uses-permission android:name="android.permission.INTERNET" />

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

            <category android:name="android.intent.category.LAUNCHER"/>
        </intent-filter>
    </activity>
    <activity
        android:name=".FileManager"
        android:theme="@style/AppTheme"/>
    <activity
        android:name=".ReaderActivity"
        android:theme="@style/MainTheme"/>
</application>

风格:

<!-- Base application theme. -->
<style name="AppTheme" parent="Theme.AppCompat.Light.DarkActionBar">
    <!-- Customize your theme here. -->
    <item name="android:windowActionBar">true</item>
    <item name="colorPrimary">@color/colorPrimary</item>
    <item name="colorPrimaryDark">@color/colorPrimaryDark</item>
    <item name="colorAccent">@color/White</item>
</style>

sec Activity的Xmlcode:

<?xml version="1.0" encoding="utf-8"?>
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
         android:layout_width="match_parent"
         android:layout_height="match_parent">

<ProgressBar
    android:layout_gravity="center_horizontal|center_vertical"
    android:visibility="invisible"
    style="?android:attr/progressBarStyleSmall"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:id="@+id/pBar"/>

<LinearLayout
    android:orientation="vertical"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:id="@+id/lin">

    <ListView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:id="@+id/list"
        android:layout_gravity="bottom"/>

</LinearLayout>

错误信息:

03-02 22:06:38.980 6648-6648/com.example.nikva.easyreading E/AndroidRuntime: 致命异常: main 进程:com.example.nikva.easyreading,PID:6648 java.lang.RuntimeException:无法启动活动 ComponentInfo{com.example.nikva.easyreading/com.example.nikva.easyreading.FileManager}:java.lang.IllegalStateException:此活动已经有一个由窗口装饰提供的操作栏。不要在主题中请求 Window.FEATURE_SUPPORT_ACTION_BAR 并将 windowActionBar 设置为 false 以使用工具栏。 在 android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2695) 在 android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2769) 在 android.app.ActivityThread.access$900(ActivityThread.java:177) 在 android.app.ActivityThread$H.handleMessage(ActivityThread.java:1430) 在 android.os.Handler.dispatchMessage(Handler.java:102) 在 android.os.Looper.loop(Looper.java:135) 在 android.app.ActivityThread.main(ActivityThread.java:5910) 在 java.lang.reflect.Method.invoke(本机方法) 在 java.lang.reflect.Method.invoke(Method.java:372) 在 com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1405) 在 com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1200) 原因:java.lang.IllegalStateException:此活动已经有一个由窗口装饰提供的操作栏。不要在主题中请求 Window.FEATURE_SUPPORT_ACTION_BAR 并将 windowActionBar 设置为 false 以使用工具栏。 在 android.support.v7.app.AppCompatDelegateImplV9.setSupportActionBar(AppCompatDelegateImplV9.java:203) 在 android.support.v7.app.AppCompatActivity.setSupportActionBar(AppCompatActivity.java:133) 在 com.example.nikva.easyreading.FileManager.onCreate(FileManager.java:52) 在 android.app.Activity.performCreate(Activity.java:6178) 在 android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1118) 在 android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2648) 在 android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2769) 在 android.app.ActivityThread.access$900(ActivityThread.java:177) 在 android.app.ActivityThread$H.handleMessage(ActivityThread.java:1430) 在 android.os.Handler.dispatchMessage(Handler.java:102) 在 android.os.Looper.loop(Looper.java:135) 在 android.app.ActivityThread.main(ActivityThread.java:5910) 在 java.lang.reflect.Method.invoke(本机方法) 在 java.lang.reflect.Method.invoke(Method.java:372) 在 com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1405) 在 com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1200)

“fileManager.class”

    package com.example.nikva.easyreading;

/**
 * Created by nikva on 08.02.2017.
 */

import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity; 
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.ProgressBar;
import android.widget.Toast;

import java.io.File;
import java.util.ArrayList;

/**
 * Created by nikitavasko11@gmail.com
 * The class that responsible for the navigation of files(File Manager).
 * @author Nikita Vasko
 */
public class FileManager extends AppCompatActivity implements    AdapterView.OnItemClickListener {

ListView listOfDirs;
ArrayList<String> paths = new ArrayList<>();
String currentPath = "";
ProgressBar pBar;
Toolbar tBar;
final private String TAG = "myTags";
private static final String KEY_LIST = "LIST";
private static final String KEY_PATH = "CURRENT_PATH";


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

    setContentView(R.layout.activity_file_manager);

    listOfDirs = (ListView) findViewById(R.id.list);
    listOfDirs.setOnItemClickListener(this);

    pBar = (ProgressBar) findViewById(R.id.pBar);

    tBar = (Toolbar) findViewById(R.id.tb);
    setSupportActionBar(tBar);


    Log.d(TAG, "Менеджер запущен.");
    if (savedInstanceState == null) {
        paths.add("/storage/emulated/0/");
        paths.add("/storage/extSdCard/");
        ArrayAdapter<String> adapter = new ArrayAdapter<>(this, android.R.layout.simple_list_item_1,
                paths);
        listOfDirs.setAdapter(adapter);//Creating a primary form of application
    }
    else{
        currentPath = savedInstanceState.get(KEY_PATH).toString();
        paths = savedInstanceState.getStringArrayList(KEY_LIST);
        ArrayAdapter<String> adapter = new ArrayAdapter<>(this, R.layout.item,
                paths);
        listOfDirs.setAdapter(adapter);
    }
}

@Override
protected void onSaveInstanceState(Bundle outState) {
    super.onSaveInstanceState(outState);
    outState.putStringArrayList(KEY_LIST, paths);
    outState.putString(KEY_PATH, currentPath);
}

@Override
public void onItemClick(AdapterView<?> adapterView, View view, int position, long id) {
    String localPath = paths.get(position);

    if (localPath.equals("...")) {
        Log.d(TAG, "Переход на уровень ниже");
        upOnLevel();
    } else {
        transition(localPath);
    }
}

/**
 * Method performs transition to new directory.
 * @param currentDirectory - current directory or file that user selected.
 */
void transition(String currentDirectory){
    if (currentDirectory.equals(".android_secure")) {
        Toast.makeText(this, "Доступ закрыт.", Toast.LENGTH_SHORT).show();
        return;
    }
    if (new File(currentPath + currentDirectory).isFile()) {
        Intent intent;
        String pathToFile = currentPath + currentDirectory;

        if (pathToFile.contains(".txt")) {
            pBar.setVisibility(View.VISIBLE);

            intent = new Intent(this, ReaderActivity.class);
            intent.putExtra("PATH_TO_BOOK", pathToFile);
            startActivity(intent);

            pBar.setVisibility(View.INVISIBLE);
        }
        else {
            Toast.makeText(this, "Эта версия работает только с txt-файлами",
                    Toast.LENGTH_SHORT).show();
        }
    }
    else {
        if (currentPath.equals("")) {
            Log.d(TAG, "Создание пути в новое хранилище.");
            currentPath = currentDirectory;
        } else {
            Log.d(TAG, "Создание пути в новую директорию");
            currentPath = currentPath + currentDirectory + "/";
        }

        File file = new File(currentPath);
        Log.d(TAG, "Создание объекта File " + file.getPath());
        if (file.isDirectory()) {
            Log.d(TAG, "Выбрана директория");
            fill(file.list());
        } else {
            Log.d(TAG, "Выбран файл");
            return;
        }
    }
}

/**
 * Method performs transition to upper level.
 */
void upOnLevel(){
    //If user want to go to the first level then paths setting manually
    Log.d(TAG, "Проверка: на каком уровне находится приложение" + new File(currentPath).getParent());
    if (new File(currentPath).getParent().equals("/storage/emulated") ||
            new File(currentPath).getParent().equals("/storage")){
        Log.d(TAG, "Возвращаемся на первый уровень");
        String [] s  = {"/storage/emulated/0/", "/storage/extSdCard/"};
        currentPath = "";
        fill(s);
    } else{
        String path = new File(currentPath).getParent() + '/';
        currentPath = "";
        transition(path);
    }
}

/**
 * Method which fills ListView with new directories or files from directory that was selected
 * by user.
 * @param dirs - list of elements from new directory.
 */
void fill(String [] dirs){
    Log.d(TAG, "Заполнение ListView");
    paths.clear();

    if (!currentPath.equals("")){
        paths.add("...");
    }

    for (int i = 0; i < dirs.length; i++){
        paths.add(dirs[i]);
    }
    Log.d(TAG, "Создание адаптера");
    ArrayAdapter<String> adapter = new ArrayAdapter<>(this, android.R.layout.simple_list_item_1,
            paths);
    listOfDirs.setAdapter(adapter);
}

}

 

【问题讨论】:

    标签: android xml android-styles


    【解决方案1】:

    问题在于您的FileManager 类集windowActionBar=false 通过样式

    在您的清单中:

    <activity android:name=".FileManager"
          android:theme="@style/AppTheme.NoActionBar"> <!-- Define custom Style -->
    

    在styles.xml中

     <style name="AppTheme.NoActionBar">
        <item name="windowActionBar">false</item>
        <item name="windowNoTitle">true</item>
    </style>
    

    因为你想使用 Activity 提供的ActionBar,所以不需要这行:

     tBar = (Toolbar) findViewById(R.id.tb);
    setSupportActionBar(tBar);      //remove this
    

    改为使用:

     ActionBar actionBar = getSupportActionBar();
     actionBar.show();
    

    【讨论】:

    • 但是我需要使用ActionBar这个Activity
    • 已发布。检查一下。
    • 知道了。谢谢。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-04-08
    相关资源
    最近更新 更多