Android更改导航栏颜色 [英] android change navigation bar color

查看:123
本文介绍了Android更改导航栏颜色的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试更改工具栏的颜色,但是似乎找不到合适的位置.以下是必要的文件和图像:

I am trying to change the color of my tool bar, but I can't seem to find the right place to do it. Below are the necessary files and images:

下面是样式,清单和Java main.

Below are the styles, manifest, and java main.

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

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

<supports-screens
    android:anyDensity="true"
    android:largeScreens="true"
    android:normalScreens="true"
    android:resizeable="true"
    android:smallScreens="true"
    android:xlargeScreens="true" />

<application
    android:allowBackup="true"
    android:icon="@mipmap/ic_launcher"
    android:label="@string/app_name"
    android:supportsRtl="true"
    android:theme="@style/myTheme"
    >
    <!-- android:theme="@style/AppTheme" -->

    <activity android:name=".MainActivity">
        <intent-filter>
            <action android:name="android.intent.action.MAIN" />
            <category android:name="android.intent.category.LAUNCHER" />
        </intent-filter>
    </activity>

    <service android:name=".MyFirebaseMessagingService">
        <intent-filter>
            <action android:name="com.google.firebase.MESSAGING_EVENT" />
        </intent-filter>
    </service>

    <service android:name=".MyFirebaseInstanceIdService">
        <intent-filter>
            <action android:name="com.google.firebase.INSTANCE_ID_EVENT" />
        </intent-filter>
    </service>

</application>

</manifest>

样式:

<resources>


    <style name="myTheme" parent="Theme.AppCompat.Light">
        <item name="android:windowNoTitle">true</item>
        <item name="homeAsUpIndicator">@drawable/ic_drawer</item>

    </style>
</resources>

java main:

java main :

import android.app.ActionBar;
import android.content.Context;
import android.content.SharedPreferences;
import android.os.Bundle;

import java.util.ArrayList;

import android.app.Activity;
import android.app.Fragment;
import android.app.FragmentManager;
import android.content.pm.ActivityInfo;
import android.content.res.Configuration;
import android.content.res.TypedArray;
import android.preference.PreferenceManager;
import android.support.v4.app.ActionBarDrawerToggle;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.webkit.WebView;
import android.widget.AdapterView;
import android.widget.EditText;
import android.widget.ListView;

import com.google.firebase.iid.FirebaseInstanceId;
import android.view.Display;
import android.graphics.Point;
import android.util.DisplayMetrics;

public class MainActivity extends AppCompatActivity {
    private DrawerLayout mDrawerLayout;
    private ListView mDrawerList;
    private ActionBarDrawerToggle mDrawerToggle;

    // nav drawer title
    private CharSequence mDrawerTitle;

    // used to store app title
    private CharSequence mTitle;

    // slide menu items
    private String[] navMenuTitles;
    private TypedArray navMenuIcons;

    private ArrayList<NavDrawerItem> navDrawerItems;
    private NavDrawerListAdapter adapter;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(life.poa.webcastman.poa1.R.layout.activity_main);

        commonfunc.myprint("#####_____mainActivity_onCreateView ");

        Display display = getWindowManager().getDefaultDisplay();
        Point size = new Point();
        display.getSize(size);
        int width = size.x;
        int height = size.y;
        commonfunc.myprint("____mainactivity-onCreate 1 : " + width + " " + height );
        DisplayMetrics metrics;
        width = 0;
        height = 0;
        metrics = new DisplayMetrics();
        getWindowManager().getDefaultDisplay().getMetrics(metrics);
        height = metrics.heightPixels;
        width = metrics.widthPixels;
        commonfunc.myprint("____mainactivity-onCreate 1 : " + width + " " + height );
        float density = this.getResources().getDisplayMetrics().density;
        if (density >= 4.0)
        {
            commonfunc.myprint( "xxxhdpi");
        }
        if (density >= 3.0)
        {
            commonfunc.myprint( "xxhdpi");
        }
        if (density >= 2.0)
        {
            commonfunc.myprint("xhdpi");
        }
        if (density >= 1.5)
        {
            commonfunc.myprint( "hdpi");
        }
        if (density >= 1.0)
        {
            commonfunc.myprint( "mdpi");
        }
        else
        {
            commonfunc.myprint("ldpi");
        }


        SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(this);
        SharedPreferences.Editor editor = preferences.edit();
        String tmpemail = preferences.getString(commonfunc.company + "email", "");
        commonfunc.myprint("mainactivity preferences email:" + commonfunc.company + "email: " + tmpemail);
        String refreshtoken = FirebaseInstanceId.getInstance().getToken();
        String preftoken = preferences.getString(commonfunc.company + "token", "");
        commonfunc.myprint("mainactivity preferences preftoken refreshtoken:" + preftoken + " <-> " + refreshtoken);
        if (refreshtoken != preftoken)
        {
            editor.putString(commonfunc.company + "token", refreshtoken );
            editor.apply();
            editor.commit();
            String tmptoken = preferences.getString(commonfunc.company + "token", "");
            commonfunc.myprint("mainactivity preferences token recheck:" + commonfunc.company + "token: " + tmptoken);
        }

        //mstarted 1/2 MainActivity my_group
        //SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(this);
        //SharedPreferences.Editor editor = preferences.edit();
        String pref_mstarted = preferences.getString(commonfunc.company + "mstarted", null);
        commonfunc.myprint("mainactivity_onCreateOptionsMenu_preferences mstarted:" + commonfunc.company + "mstarted: " + pref_mstarted);
        editor.putString(commonfunc.company + "mstarted", null);
        editor.apply();
        editor.commit();
        pref_mstarted = preferences.getString(commonfunc.company + "mstarted", null);
        commonfunc.myprint("mainactivity_onCreateOptionsMenu_preferences mstarted:" + commonfunc.company + "mstarted: " + pref_mstarted);


        mTitle = mDrawerTitle = getTitle();

        // load slide menu items
        navMenuTitles = getResources().getStringArray(life.poa.webcastman.poa1.R.array.nav_drawer_items);

        // nav drawer icons from resources
        navMenuIcons = getResources()
                .obtainTypedArray(life.poa.webcastman.poa1.R.array.nav_drawer_icons);

        mDrawerLayout = (DrawerLayout) findViewById(life.poa.webcastman.poa1.R.id.drawer_layout);
        mDrawerList = (ListView) findViewById(life.poa.webcastman.poa1.R.id.list_slidermenu);

        navDrawerItems = new ArrayList<NavDrawerItem>();

        // adding nav drawer items to array
        // Home
        navDrawerItems.add(new NavDrawerItem(navMenuTitles[0], navMenuIcons.getResourceId(0, -1)));
        // Login
        navDrawerItems.add(new NavDrawerItem(navMenuTitles[1], navMenuIcons.getResourceId(1, -1)));
        // Create Account
        navDrawerItems.add(new NavDrawerItem(navMenuTitles[2], navMenuIcons.getResourceId(2, -1)));
        // Calendar
        navDrawerItems.add(new NavDrawerItem(navMenuTitles[3], navMenuIcons.getResourceId(3, -1)));
        // Live Webcast
        navDrawerItems.add(new NavDrawerItem(navMenuTitles[4], navMenuIcons.getResourceId(4, -1)));
        // My Groups
        navDrawerItems.add(new NavDrawerItem(navMenuTitles[5], navMenuIcons.getResourceId(5, -1)));
        // Sample
        navDrawerItems.add(new NavDrawerItem(navMenuTitles[6], navMenuIcons.getResourceId(6, -1)));
        // Recycle the typed array
        navMenuIcons.recycle();

        mDrawerList.setOnItemClickListener(new SlideMenuClickListener());

        // setting the nav drawer list adapter
        adapter = new NavDrawerListAdapter(getApplicationContext(),
                navDrawerItems);
        mDrawerList.setAdapter(adapter);

        // enabling action bar app icon and behaving it as toggle button
        //getActionBar().setDisplayHomeAsUpEnabled(true);
        //getActionBar().setHomeButtonEnabled(true);
        //getActionBar().setDisplayShowHomeEnabled(false);

        getSupportActionBar().setDisplayHomeAsUpEnabled(true);
        getSupportActionBar().setDisplayHomeAsUpEnabled(true);
        getSupportActionBar().setHomeButtonEnabled(true);


        mDrawerToggle = new ActionBarDrawerToggle(this, mDrawerLayout,
                life.poa.webcastman.poa1.R.drawable.ic_drawer, //nav menu toggle icon
                life.poa.webcastman.poa1.R.string.app_name, // nav drawer open - description for accessibility
                life.poa.webcastman.poa1.R.string.app_name // nav drawer close - description for accessibility
        ) {
            public void onDrawerClosed(View view) {
                commonfunc.myprint("mainActivity_onDrawerClosed ");
                getSupportActionBar().setTitle(mTitle);
                // calling onPrepareOptionsMenu() to show action bar icons
                invalidateOptionsMenu();
            }

            public void onDrawerOpened(View drawerView) {
                commonfunc.myprint("mainActivity_onDrawerOpened ");
                //Hide Keyboard GB
                InputMethodManager imm = (InputMethodManager)getSystemService(Context.INPUT_METHOD_SERVICE);
                imm.hideSoftInputFromWindow(drawerView.getWindowToken(), 0);
                getSupportActionBar().setTitle(mTitle);

                // calling onPrepareOptionsMenu() to hide action bar icons
                invalidateOptionsMenu();
            }
        };
        mDrawerLayout.setDrawerListener(mDrawerToggle);

        if (savedInstanceState == null) {
            // on first time display view for first nav item
            displayView(0);
        }
    }

    /**
     * Slide menu item click listener
     * */
    private class SlideMenuClickListener implements
            ListView.OnItemClickListener {
        @Override
        public void onItemClick(AdapterView<?> parent, View view, int position,
                                long id) {
            commonfunc.myprint("mainActivity_SlideMenuClickListener ");
            // display view for selected nav drawer item
            displayView(position);
        }
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        commonfunc.myprint("mainActivity_onCreateOptionsMenu ");
        getMenuInflater().inflate(life.poa.webcastman.poa1.R.menu.main, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        commonfunc.myprint("mainActivity_onOptionsItemSelected ");
        // toggle nav drawer on selecting action bar app icon/title
        if (mDrawerToggle.onOptionsItemSelected(item)) {
            return true;
        }
        // Handle action bar actions click
        switch (item.getItemId()) {
            case life.poa.webcastman.poa1.R.id.action_settings:
                return true;
            default:
                return super.onOptionsItemSelected(item);
        }
    }

    /* *
     * Called when invalidateOptionsMenu() is triggered
     */
    @Override
    public boolean onPrepareOptionsMenu(Menu menu) {
        commonfunc.myprint("mainActivity_onPrepareOptionsMenu ");
        // if nav drawer is opened, hide the action items
        boolean drawerOpen = mDrawerLayout.isDrawerOpen(mDrawerList);
        menu.findItem(life.poa.webcastman.poa1.R.id.action_settings).setVisible(!drawerOpen);
        return super.onPrepareOptionsMenu(menu);
    }

    /**
     * Diplaying fragment view for selected nav drawer list item
     * */
    private void displayView(int position) {
        commonfunc.myprint("#####_____mainActivity_displayView ");
        // update the main content by replacing fragments
        Fragment fragment = null;

        // We allow the Sensor to be used in all instances by default
        setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_SENSOR);
        switch (position) {
            case 0:
                fragment = new HomeFragment();
                break;
            case 1:
                fragment = new login_login();
                break;
            case 2:
                fragment = new login_create();
                break;
            case 3:
                fragment = new calendar();
                break;
            case 4:
                fragment = new WhatsHotFragment();
                break;
            case 5:
                fragment = new my_group();
                break;
            case 6:
                fragment = new my_table();
                break;

            default:
                // In just this one instance, we turn the sensor off
                // Until a different menu item is selected, which re-enables it
                //setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_NOSENSOR);
                break;
        }

        if (fragment != null) {
            FragmentManager fragmentManager = getFragmentManager();
            fragmentManager.beginTransaction()
                    .replace(life.poa.webcastman.poa1.R.id.frame_container, fragment).commit();

            // update selected item and title, then close the drawer
            mDrawerList.setItemChecked(position, true);
            mDrawerList.setSelection(position);
            setTitle(navMenuTitles[position]);
            mDrawerLayout.closeDrawer(mDrawerList);
        } else {
            // error in creating fragment
            commonfunc.myprint("MainActivity Error in creating fragment");
        }
    }

    @Override
    public void setTitle(CharSequence title) {
        commonfunc.myprint("mainActivity_setTitle ");
        mTitle = title;
        //getActionBar().setTitle(mTitle);

        getSupportActionBar().setTitle(mTitle);
    }

    /**
     * When using the ActionBarDrawerToggle, you must call it during
     * onPostCreate() and onConfigurationChanged()...
     */

    @Override
    protected void onPostCreate(Bundle savedInstanceState) {
        super.onPostCreate(savedInstanceState);
        // Sync the toggle state after onRestoreInstanceState has occurred.
        commonfunc.myprint("mainActivity_onPostCreate ");
        mDrawerToggle.syncState();
    }

    @Override
    public void onConfigurationChanged(Configuration newConfig) {
        super.onConfigurationChanged(newConfig);
        // Pass any configuration change to the drawer toggls
        commonfunc.myprint("mainActivity_onConfigurationChanged ");
        mDrawerToggle.onConfigurationChanged(newConfig);
    }

}

推荐答案

您可以通过添加以下样式的语句来做到这一点

You can do it by adding this statement in styles

<item name="android:navigationBarColor">@color/theme_color</item>

或在主Java中

window.setNavigationBarColor(@ColorInt int color);

这篇关于Android更改导航栏颜色的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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