当前位置: 首页 > 知识库问答 >
问题:

android更改导航栏颜色[重复]

嵇俊德
2023-03-14

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

下面是样式、清单和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:

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);
    }

}

共有2个答案

闾丘玺
2023-03-14
mDrawerLayout.setBackgroundResource(int);

如果您使用的是NavigationView,请选择并提供此选项

 android:background="@color/color_navigation_list_background"
袁智明
2023-03-14

可以通过在样式中添加此语句来实现

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

或者这个在主java中

window.setNavigationBarColor(@ColorInt int color);
 类似资料:
  • 在我的应用程序中,我需要更改底部导航栏的颜色。我看了很多帖子,但没有找到解决办法。我正在使用appCompat库。 v21/样式。xml

  • 问题内容: 我正在尝试更改导航器栏的颜色,但是我发现只有导航器是根导航器,这才是不可能的。 我正在尝试: 我所有与导航器控制器有关。但是什么都没有改变。实际上,我试图从情节提要中进行相同的操作,但只有在我处于第一个导航器中时,它才有效。 我试图阅读与此问题有关的所有内容,但一无所获 我可以像这样将任何项目添加到导航栏 问题答案: 实际上,我发现该解决方案将用于: 然后在每个视图控制器中,我们需要另

  • 我尝试了很多方法来改变导航栏的颜色,比如 AndroidLollipop更改导航栏颜色 android更改导航栏颜色 如何更改系统导航栏颜色 什么都不管用 我将该项目添加到样式中。xml-使用Android 8.1 任何人都知道在Xamarin做这件事的最佳方式是什么。Android 更新:我在样式文件中尝试了以下代码

  • 我想要一个半透明的状态栏和导航栏,其他颜色不能像蓝色或白色那样半透明 我的代码 活动 状态栏半透明良好,但导航栏颜色不变。为什么? 导航栏

  • 我现在有一段html,它代表我的导航栏的相关部分: 我有一个css,我希望用它来改变导航栏的文本颜色: 唯一的问题是文本颜色保持不变。我还看到一个非常相似的问题没有解决。我打赌谁能解决这个问题,谁就能解决另一个问题。

  • 问题内容: 我正在使用Picker View,允许用户为整个应用程序选择颜色主题。 我计划更改导航栏,背景以及选项卡栏(如果可能)的颜色。 我一直在研究如何执行此操作,但找不到任何Swift示例。谁能给我一个示例代码,我将需要使用该代码来更改导航栏颜色和导航栏文本颜色? 设置了Picker View,我只是在寻找更改UI颜色的代码。 问题答案: 导航栏: 用所需的UIColor替换greenCol