【问题标题】:android - Toolbar not displaying in activityandroid - 工具栏未显示在活动中
【发布时间】:2015-02-04 16:28:38
【问题描述】:

开发壁纸应用程序,并致力于迁移到 API 21 并移除 ActionBar 以支持 Toolbar。话虽如此,我正在尝试使用 v7-support 库。发生的情况基本上是工具栏应该在哪里有一个灰色轮廓,但它永远不会出现。

WallpaperActivity.java:

package com.death2all110.blisspapers;

import android.app.Fragment;
import android.app.FragmentManager;
import android.app.FragmentTransaction;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.graphics.drawable.Drawable;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Environment;
import android.support.v7.app.ActionBarActivity;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;

import com.koushikdutta.urlimageviewhelper.UrlImageViewCallback;
import com.koushikdutta.urlimageviewhelper.UrlImageViewHelper;

import java.io.BufferedInputStream;
import java.io.File;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.URL;
import java.net.URLConnection;
import java.util.ArrayList;

public class WallpaperActivity extends ActionBarActivity {

    public final String TAG = "BlissPapers";
    protected static final String MANIFEST = "wallpaper_manifest.xml";
    protected static final int THUMBS_TO_SHOW = 4;

    /*
     * pull the manifest from the web server specified in config.xml or pull
     * wallpaper_manifest.xml from local assets/ folder for testing
     */
    public static final boolean USE_LOCAL_MANIFEST = false;

    ArrayList<WallpaperCategory> categories = null;
    ProgressDialog mLoadingDialog;



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

        Window window = getWindow();
        window.addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS);
        window.clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
        window.setStatusBarColor(getResources().getColor(R.color.primary_dark));

        setContentView(R.layout.activity_wallpaper);

        mLoadingDialog = new ProgressDialog(this);
        mLoadingDialog.setCancelable(false);
        mLoadingDialog.setIndeterminate(true);
        mLoadingDialog.setMessage("Retreiving wallpapers from server...");

        mLoadingDialog.show();
        new LoadWallpaperManifest().execute();

        Toolbar ab = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(ab);
        getSupportActionBar().setTitle("Bliss Papers");
        getSupportActionBar().setDisplayShowTitleEnabled(true);

        UrlImageViewHelper.setErrorDrawable(getResources().getDrawable(com.death2all110.blisspapers.R.drawable.ic_error));

    }

    @Override
    public void onResume() {
        super.onResume();
        Wallpaper.wallpapersCreated = 0;
    }

    protected void loadPreviewFragment() {
        WallpaperPreviewFragment fragment = new WallpaperPreviewFragment();
        FragmentManager fragmentManager = getFragmentManager();
        FragmentTransaction ft = fragmentManager.beginTransaction();
        ft.add(android.R.id.content, fragment);
        ft.commit();
    }


    public static class WallpaperPreviewFragment extends Fragment {

        static final String TAG = "PreviewFragment";
        WallpaperActivity mActivity;
        View mView;

        public int currentPage = -1;
        public int highestExistingIndex = 0;
        Button back;
        Button next;
        TextView pageNum;
        ThumbnailView[] thumbs;
        protected int selectedCategory = 0; // *should* be <ALL> wallpapers

        @Override
        public void onActivityCreated(Bundle savedInstanceState) {
            super.onActivityCreated(savedInstanceState);
            mActivity = (WallpaperActivity) getActivity();
            next(); // load initial page
        }

        public void setCategory(int cat) {
            selectedCategory = cat;
            currentPage = -1;
            next();
        }

        @Override
        public View onCreateView(LayoutInflater inflater, ViewGroup container,
                Bundle savedInstanceState) {

            mView = inflater.inflate(com.death2all110.blisspapers.R.layout.activity_wallpaper, container, false);

            back = (Button) mView.findViewById(com.death2all110.blisspapers.R.id.backButton);
            next = (Button) mView.findViewById(com.death2all110.blisspapers.R.id.nextButton);
            pageNum = (TextView) mView.findViewById(com.death2all110.blisspapers.R.id.textView1);

            thumbs = new ThumbnailView[THUMBS_TO_SHOW];
            thumbs[0] = (ThumbnailView) mView.findViewById(com.death2all110.blisspapers.R.id.imageView1);
            thumbs[1] = (ThumbnailView) mView.findViewById(com.death2all110.blisspapers.R.id.imageView2);
            thumbs[2] = (ThumbnailView) mView.findViewById(com.death2all110.blisspapers.R.id.imageView3);
            thumbs[3] = (ThumbnailView) mView.findViewById(com.death2all110.blisspapers.R.id.imageView4);

            next.setOnClickListener(new View.OnClickListener() {
                public void onClick(View v) {
                    next();
                }
            });

            back.setOnClickListener(new View.OnClickListener() {
                public void onClick(View v) {
                    previous();
                }
            });

            return mView;
        }

        public ArrayList<WallpaperCategory> getCategories() {
            return mActivity.categories;
        }

        protected Wallpaper getWallpaper(int realIndex) {
            return getCategories().get(selectedCategory).getWallpapers().get(realIndex);
        }

        protected void setThumbs() {
            for (ThumbnailView v : thumbs)
                v.setVisibility(View.INVISIBLE);

            final int numWallpapersInCategory = getCategories().get(selectedCategory)
                    .getWallpapers().size();
            boolean enableForward = true;

            for (int i = 0; i < thumbs.length; i++) {
                final int realIndex = (currentPage * thumbs.length + i);
                if (realIndex >= (numWallpapersInCategory - 1)) {
                    enableForward = false;
                    break;
                }

                Wallpaper w = getWallpaper(realIndex);
                thumbs[i].setOnClickListener(null);
                thumbs[i].getName().setText(w.getName());
                thumbs[i].getAuthor().setText(w.getAuthor());
                UrlImageViewHelper.setUrlDrawable(thumbs[i].getThumbnail(), w.getThumbUrl(),
                        com.death2all110.blisspapers.R.drawable.ic_placeholder, new ThumbnailCallBack(w, realIndex));
            }

            back.setEnabled(currentPage != 0);
            next.setEnabled(enableForward);
        }

        public void next() {
            getNextButton().setEnabled(false);
            pageNum.setText(getResources().getString(com.death2all110.blisspapers.R.string.page) + " " + (++currentPage + 1));

            setThumbs();
        }

        public void previous() {
            pageNum.setText(getResources().getString(com.death2all110.blisspapers.R.string.page) + " " + (--currentPage + 1));

            setThumbs();
        }

        protected void skipToPage(int page) {
            if (page < currentPage) {
                while (page < currentPage) {
                    previous(); // should subtract page
                }
            } else if (page > currentPage) {
                while (page > currentPage) {
                    next();
                }
            }
        }

        public void jumpTo() {
            // View view = getLayoutInflater().inflate(R.layout.dialog_jumpto,
            // null);
            // final EditText e = (EditText) view.findViewById(R.id.pageNumber);
            // AlertDialog.Builder j = new AlertDialog.Builder(this);
            // j.setTitle(R.string.jump2);
            // j.setView(view);
            // j.setPositiveButton(android.R.string.ok, new
            // DialogInterface.OnClickListener() {
            //
            // public void onClick(DialogInterface dialog, int which) {
            // skipToPage(Integer.parseInt(e.getText().toString()));
            // }
            // });
            // j.setNegativeButton(android.R.string.no, new
            // DialogInterface.OnClickListener() {
            //
            // public void onClick(DialogInterface dialog, int which) {
            // dialog.cancel();
            // }
            // });
            // j.create().show();
        }

        protected View getThumbView(int i) {
            if (thumbs != null && thumbs.length > 0)
                return thumbs[i];
            else
                return null;
        }

        protected Button getNextButton() {
            return next;
        }

        protected Button getPreviousButton() {
            return back;
        }

        @Override
        public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
            super.onCreateOptionsMenu(menu, inflater);
        }

        public boolean onOptionsItemSelected(MenuItem item) {
            switch (item.getItemId()) {
                case com.death2all110.blisspapers.R.id.jump:
                    jumpTo();
                    return true;
                default:
                    return super.onOptionsItemSelected(item);
            }
        }

        class ThumbnailCallBack implements UrlImageViewCallback {

            Wallpaper wall;
            int index;

            public ThumbnailCallBack(Wallpaper wall, int index) {
                this.wall = wall;
                this.index = index;
            }

            @Override
            public void onLoaded(ImageView imageView, Drawable loadedDrawable, String url,
                    boolean loadedFromCache, boolean error) {

                final int relativeIndex = index % 4;
                if (!error) {
                    getThumbView(relativeIndex).setOnClickListener(
                            new ThumbnailClickListener(wall));
                }
                getThumbView(relativeIndex).setVisibility(View.VISIBLE);

                if (relativeIndex == 3)
                    getNextButton().setEnabled(true);
            }
        }

        class ThumbnailClickListener implements View.OnClickListener {
            Wallpaper wall;

            public ThumbnailClickListener(Wallpaper wallpaper) {
                this.wall = wallpaper;
            }

            @Override
            public void onClick(View v) {
                Intent preview = new Intent(mActivity, Preview.class);
                preview.putExtra("wp", wall.getUrl());
                startActivity(preview);
            }
        }
    }



    public static String getDlDir(Context c) {
        String configFolder = getResourceString(c, com.death2all110.blisspapers.R.string.config_wallpaper_download_loc);
        if (configFolder != null && !configFolder.isEmpty()) {
            return new File(Environment.getExternalStorageDirectory(), configFolder)
                    .getAbsolutePath() + "/";
        } else {
            return Environment.getExternalStorageDirectory().getAbsolutePath();
        }
    }

    public static String getSvDir(Context c) {
        String configFolder = getResourceString(c, com.death2all110.blisspapers.R.string.config_wallpaper_sdcard_dl_location);
        if (configFolder != null && !configFolder.isEmpty()) {
            return new File(Environment.getExternalStorageDirectory(), configFolder)
                    .getAbsolutePath() + "/";
        } else {
            return null;
        }
    }

    protected String getWallpaperDestinationPath() {
        String configFolder = getResourceString(com.death2all110.blisspapers.R.string.config_wallpaper_sdcard_dl_location);
        if (configFolder != null && !configFolder.isEmpty()) {
            return new File(Environment.getExternalStorageDirectory(), configFolder)
                    .getAbsolutePath();
        }
        // couldn't find resource?
        return null;
    }

    protected String getResourceString(int stringId) {
        return getApplicationContext().getResources().getString(stringId);
    }

    public static String getResourceString(Context c, int id) {
        return c.getResources().getString(id);
    }

    private class LoadWallpaperManifest extends
            AsyncTask<Void, Boolean, ArrayList<WallpaperCategory>> {

        @Override
        protected ArrayList<WallpaperCategory> doInBackground(Void... v) {

            try {
                InputStream input = null;

                if (USE_LOCAL_MANIFEST) {
                    input = getApplicationContext().getAssets().open(MANIFEST);
                } else {
                    URL url = new URL(getResourceString(com.death2all110.blisspapers.R.string.config_wallpaper_manifest_url));
                    URLConnection connection = url.openConnection();
                    connection.connect();
                    // this will be useful so that you can show a typical
                    // 0-100%
                    // progress bar
                    int fileLength = connection.getContentLength();

                    // download the file
                    input = new BufferedInputStream(url.openStream());
                }
                OutputStream output = getApplicationContext().openFileOutput(
                        MANIFEST, MODE_PRIVATE);

                byte data[] = new byte[1024];
                long total = 0;
                int count;
                while ((count = input.read(data)) != -1) {
                    total += count;
                    // publishing the progress....
                    // publishProgress((int) (total * 100 / fileLength));
                    output.write(data, 0, count);
                }

                output.flush();
                output.close();
                input.close();

                // file finished downloading, parse it!
                ManifestXmlParser parser = new ManifestXmlParser();
                return parser.parse(new File(getApplicationContext().getFilesDir(), MANIFEST),
                        getApplicationContext());
            } catch (Exception e) {
                Log.d(TAG, "Exception!", e);
            }
            return null;
        }

        @Override
        protected void onPostExecute(ArrayList<WallpaperCategory> result) {
            categories = result;
            if (categories != null)
                loadPreviewFragment();

            mLoadingDialog.cancel();
            super.onPostExecute(result);
        }
    }

}

这里是activity_wallpaper.xml

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent" >


    <View
        android:id="@+id/strut"
        android:layout_width="0dp"
        android:layout_height="0dp"
        android:layout_centerHorizontal="true" />

    <Button
        android:id="@+id/backButton"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:layout_alignParentBottom="true"
        android:layout_alignParentLeft="true"
        android:layout_alignRight="@id/strut"
        android:layout_marginBottom="5dp"
        android:text="@string/back" />

    <Button
        android:id="@+id/nextButton"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:layout_alignLeft="@id/strut"
        android:layout_alignParentBottom="true"
        android:layout_alignParentRight="true"
        android:layout_marginBottom="5dp"
        android:text="@string/next" />

    <TextView
        android:id="@+id/textView1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_above="@+id/backButton"
        android:layout_centerHorizontal="true"
        android:layout_marginBottom="5dp"
        android:text="@string/page" />

    <LinearLayout
        android:id="@+id/LinearLayout1"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_above="@id/textView1"
        android:layout_alignParentRight="true"
        android:layout_alignParentTop="true"
        android:layout_marginBottom="5dp"
        android:orientation="vertical" >

        <android.support.v7.widget.Toolbar
            android:id="@+id/toolbar"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:minHeight="?android:attr/actionBarSize"
            android:background="?android:attr/colorPrimary" />

        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="0dp"
            android:layout_weight="1"
            android:orientation="horizontal" >

            <com.death2all110.blisspapers.ThumbnailView
                android:id="@+id/imageView1"
                android:layout_width="0dp"
                android:layout_height="match_parent"
                android:layout_marginBottom="5dp"
                android:layout_marginLeft="5dp"
                android:layout_marginRight="5dp"
                android:layout_marginTop="5dp"
                android:layout_weight="1" />

            <com.death2all110.blisspapers.ThumbnailView
                android:id="@+id/imageView2"
                android:layout_width="0dp"
                android:layout_height="match_parent"
                android:layout_marginBottom="5dp"
                android:layout_marginLeft="5dp"
                android:layout_marginRight="5dp"
                android:layout_marginTop="5dp"
                android:layout_weight="1" />
        </LinearLayout>

        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="0dp"
            android:layout_weight="1"
            android:orientation="horizontal" >

            <com.death2all110.blisspapers.ThumbnailView
                android:id="@+id/imageView3"
                android:layout_width="0dp"
                android:layout_height="match_parent"
                android:layout_marginBottom="5dp"
                android:layout_marginLeft="5dp"
                android:layout_marginRight="5dp"
                android:layout_marginTop="5dp"
                android:layout_weight="1" />

            <com.death2all110.blisspapers.ThumbnailView
                android:id="@+id/imageView4"
                android:layout_width="0dp"
                android:layout_height="match_parent"
                android:layout_marginBottom="5dp"
                android:layout_marginLeft="5dp"
                android:layout_marginRight="5dp"
                android:layout_marginTop="5dp"
                android:layout_weight="1" />
        </LinearLayout>
    </LinearLayout>

</RelativeLayout>

styles.xml:

<resources>

    <style name="Theme.Bliss" parent="Theme.AppCompat.NoActionBar">
    <!-- Main theme colors -->
    <!--   your app branding color for the app bar -->
    <item name="colorPrimary">@color/primary</item>
    <!--   darker variant for the status bar and contextual app bars -->
    <item name="colorPrimaryDark">@color/primary_dark</item>
    <!--   theme UI controls like checkboxes and text fields -->
    <item name="colorAccent">@color/accent</item>
    </style>

</resources>

如果我从 onCreate 方法中删除 setContentView,我会收到错误:

java.lang.NullPointerException:尝试在空对象引用上调用虚拟方法“java.lang.CharSequence android.support.v7.widget.Toolbar.getTitle()”

关于我可以做些什么来纠正这个问题的任何想法?

截图:

【问题讨论】:

  • 你不需要打电话给getSupportActionBar().show();,不过我不确定这是否能解决你的问题。
  • @Philio 这是为了展示它。不过我会删除它。
  • 我还建议删除 getWindow().requestFeature(Window.FEATURE_ACTION_BAR); 你也不需要这个来使用工具栏
  • 尝试注释掉除 setContentView 和 setSupportActionBar(以及相应的代码)之外的所有内容,看看是否有效。
  • @Philio 做到了,并将工具栏移到 onCreate 方法和同样的问题,只是工具栏应该在哪里的轮廓

标签: java android android-support-library material-design


【解决方案1】:

我发现我需要这样做

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

在我的活动布局文件中,因为我在自己的 xml 文件中定义了我的工具栏布局。

【讨论】:

    【解决方案2】:

    FWIW - 我刚刚将一些 ABS 的东西改装到你正在使用的新工具栏的东西上,并且在所有片段、活动中都没有出现标题的一些问题......有些工作有些没有。有不同的结果非常令人沮丧。由于继承和对“super.onCreate()”的调用,不得不在我认为不需要它的地方复制以下代码..

     toolbar = (Toolbar) findViewById(R.id.toolbar);
        if (toolbar != null) {
            setSupportActionBar(toolbar);
            getSupportActionBar().setDisplayHomeAsUpEnabled(true);
            getSupportActionBar().setDisplayShowTitleEnabled(true);
    

    在没有显示的活动/片段中到处填充上述代码后,问题就解决了。

    你的标题闪现然后消失真的很奇怪......有些东西正在重新绘制视图!

    【讨论】:

    • 刚刚试过这个。同样的问题。这真是令人沮丧,哈哈。
    • 在调用堆栈的下方尝试如何... onStart, onResume ??
    • 一定是 AppCompat 库中的错误。我切换到使用材料主题和 API21 没有应用兼容的东西,一切都按预期工作。
    【解决方案3】:

    您需要在布局中添加 android.supprt.v7.widget.Toolbar,然后在 ActionBarActivity 的 onCreate 方法中执行此操作

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

    另外,请确保您的主题使用 Theme.AppCompat.NoActionBar(或 Theme.AppCompat.Light.NoActionBar)

    【讨论】:

    • 我的 WallpaperActivity 和 activity_wallpaper.xml 中已经有了它
    • 好吧,我修复了我的样式以设置正确的父主题。现在显示工具栏。但我无法让标题出现。我从 styles.xml 中删除了 android:windowNoTitle 和 windowNoActionBar 行。我也试过 getSupportActionBar.setTitle("Title");和 getSupportActionBar.setDisplayShowTitleEnabled(true);但标题闪烁然后消失
    • 解决了所有问题。使用常规材质主题而不是 AppCompat 并使用常规工具栏 API。这让我想要的东西以及标题得以保留。谢谢!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-08-19
    • 2016-08-28
    相关资源
    最近更新 更多