简体   繁体   English

从操作栏中删除抽屉导航图标

[英]Remove drawer navigation icon from Action bar

I would like to remove the default icon of navigation drawer from action bar and move my logo to the left corner.我想从操作栏中删除导航抽屉的默认图标并将我的徽标移动到左角。

My action bar:我的操作栏:

在此处输入图片说明

Piece of MainActivity: MainActivity 的一部分:

EDITED://编辑://

As you can see, I added logo instead of title如您所见,我添加了徽标而不是标题

 public class MainActivity extends AppCompatActivity
        implements NavigationView.OnNavigationItemSelectedListener {

    private int REQUEST_CAMERA = 0, SELECT_FILE = 1;
    private Button btnSelect;
    private ImageView ivImage;
    private String userChoosenTask;
    private SharedPreferences pref, pref2;
    private String jsonResult;
    public static Boolean isBookmarkSelected = false;
    private String url = "http://nwbrn.ayz.pl/Bookmark.php";
    private Menu menu;
    private MenuItem starMenu;
    private MenuItem shareMenu;
    private Bookmark bookmark;

    private TextView textView;
    private TextView textView2;
    private TextView textView3;

    private TabLayout tabLayout;
    private ViewPager viewPager;
    private FloatingActionButton floatingActionButton1, floatingActionButton2, floatingActionButton3;
    public static FloatingActionMenu materialDesignFAM;
    public static boolean fabVisible;


    private static final String TAG = MainActivity.class.getSimpleName();
    private BroadcastReceiver mRegistrationBroadcastReceiver;
    private TextView txtRegId, txtMessage;

    private int[] tabIcons = {
            R.drawable.ic_tab_one,
            R.drawable.ic_tab_two,
            R.drawable.ic_tab_profile
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        FirebaseApp.initializeApp(this);

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

        setSupportActionBar(toolbar);
        getSupportActionBar().setDisplayShowTitleEnabled(false);
        getSupportActionBar().setDisplayHomeAsUpEnabled(false);

//        getSupportActionBar().setDisplayUseLogoEnabled(true);
//        getSupportActionBar().setDisplayShowHomeEnabled(true);
        getSupportActionBar().setIcon(R.drawable.logo2);


//        txtRegId = (TextView) findViewById(R.id.txt_reg_id);
//        txtMessage = (TextView) findViewById(R.id.txt_push_message);

        pref = PreferenceManager.getDefaultSharedPreferences(getBaseContext());

        String name = pref.getString(Constants.NAME, "");
        String avatar = pref.getString(Constants.AVATAR, "");

        textView = (TextView) findViewById(R.id.textView);
        textView2 = (TextView) findViewById(R.id.textView2);
        textView3 = (TextView) findViewById(R.id.textView3);

        textView.setText(pref.getString(Constants.FULLNAME, ""));
        textView2.setText("@" + pref.getString(Constants.NAME, ""));

        Spannable span = new SpannableString("made with   by @Marcin.Brzozowski");  // or set your text manually
        Drawable drawable;
        drawable = getResources().getDrawable(R.drawable.madewithlove_heart);
        drawable.setBounds(8, 8, drawable.getIntrinsicWidth(), drawable.getIntrinsicHeight());
        ImageSpan imageSpan = new ImageSpan(drawable);
        span.setSpan(imageSpan, 9, 11, Spannable.SPAN_INCLUSIVE_EXCLUSIVE);

        textView3.setText(span);

        FirebaseInstanceId.getInstance().getToken();
        mRegistrationBroadcastReceiver = new BroadcastReceiver() {
            @Override
            public void onReceive(Context context, Intent intent) {

                // checking for type intent filter
                if (intent.getAction().equals(Config.REGISTRATION_COMPLETE)) {
                    // gcm successfully registered
                    // now subscribe to `global` topic to receive app wide notifications
                    FirebaseMessaging.getInstance().subscribeToTopic(Config.TOPIC_GLOBAL);

//                    displayFirebaseRegId();

                } else if (intent.getAction().equals(Config.PUSH_NOTIFICATION)) {
                    // new push notification is received

                    String message = intent.getStringExtra("message");

                    Toast.makeText(getApplicationContext(), "Push notification: " + message, Toast.LENGTH_LONG).show();

//                    txtMessage.setText(message);
                }
            }
        };

//        displayFirebaseRegId();

//        textView3.setText("Made with love by MB");
//        textView3.setGravity(Gravity.CENTER | Gravity.RIGHT);

        ivImage = (ImageView) findViewById(R.id.ivImage);
//        Picasso.with(getBaseContext()).invalidate(pref.getString(Constants.AVATAR, ""));
        Picasso.with(getBaseContext())
                .load(Uri.parse(pref.getString(Constants.AVATAR, "")))
                .resize(200, 200).centerCrop()
                .memoryPolicy(MemoryPolicy.NO_CACHE )
                .networkPolicy(NetworkPolicy.NO_CACHE)
                .noFade()
                .into(ivImage);

        final String[] menus = {"Home", "My Groups", "Change Group", "Settings"};

        DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
        ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(
                this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
        drawer.setDrawerListener(toggle);
        toggle.syncState();

        final TabsFragment galleryFragment = new TabsFragment();

        getSupportFragmentManager().beginTransaction()
                .replace(R.id.content_frame, galleryFragment)
                .addToBackStack(null)
                .commit();
        elevateActionBar(false);

        NavigationView navigationView = (NavigationView) findViewById(R.id.navigation);
        navigationView.setNavigationItemSelectedListener(this);

        //CustomAdapter we created for Customize Navigation
        ListView navlist = (ListView) findViewById(R.id.list);
        NavPanelListAdapter adapter = new NavPanelListAdapter(this, menus);
        navlist.setAdapter(adapter);

        navlist.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {

                String selectedMenu = menus[i];

                switch (selectedMenu) {

                    case "Home":
//                        TabsFragment groupFragment = new TabsFragment();

                        getSupportFragmentManager().beginTransaction()
                                .setCustomAnimations(R.anim.enter,R.anim.exit,R.anim.pop_enter, R.anim.pop_exit)
                                .replace(R.id.content_frame, galleryFragment)
                                .addToBackStack(null)
                                .commit();
                        elevateActionBar(false);

                        break;

                    case "My Groups":
                        MyGroupsFragment groupsFragment = new MyGroupsFragment();

                        getSupportFragmentManager().beginTransaction()
                                .setCustomAnimations(R.anim.enter,R.anim.exit,R.anim.pop_enter, R.anim.pop_exit)
                                .replace(R.id.content_frame, groupsFragment)
                                .addToBackStack(null)
                                .commit();
                        elevateActionBar(true);

                        break;

                    case "Change Group":
                        ChangeGroupFragment changeGroupFragment = new ChangeGroupFragment();
                        getSupportFragmentManager().beginTransaction()
                                .setCustomAnimations(R.anim.enter,R.anim.exit,R.anim.pop_enter, R.anim.pop_exit)
                                .replace(R.id.content_frame, changeGroupFragment)
                                .addToBackStack(null)
                                .commit();
                        elevateActionBar(true);

                        break;

                    case "Settings":
                        SettingsFragment settingsFragment = new SettingsFragment();
                        getSupportFragmentManager().beginTransaction()
                                .setCustomAnimations(R.anim.enter,R.anim.exit,R.anim.pop_enter, R.anim.pop_exit)
                                .replace(R.id.content_frame, settingsFragment)
                                .addToBackStack(null)
                                .commit();
                        elevateActionBar(true);

                        break;
                    default:
                        break;
                }

                DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
                drawer.closeDrawer(GravityCompat.START);
            }
        });
    }

    @Override
    public void onBackPressed() {
        DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
        if (drawer.isDrawerOpen(GravityCompat.START)) {
            drawer.closeDrawer(GravityCompat.START);
        } else {
            super.onBackPressed();
        }
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        this.menu = menu;

        String email = pref.getString(Constants.EMAIL, "");
        System.out.println(email);
        String id_group = pref.getString(Constants.ID_GROUP, "");
        System.out.println(id_group);
        String _nameOfGroup = pref.getString(Constants.NAZWA, "");
        System.out.println(_nameOfGroup);


        onBookmarkItemSelected(email, id_group, _nameOfGroup);

        starMenu = menu.add("Added to Favourites");
        shareMenu = menu.add("Share files.");

        shareMenu.setIcon(R.drawable.share).setShowAsAction(MenuItem.SHOW_AS_ACTION_ALWAYS);

        if(isBookmarkSelected == true) {
            starMenu.setIcon(R.drawable.ic_star_black).setShowAsAction(MenuItem.SHOW_AS_ACTION_ALWAYS);
        }
        else {
            starMenu.setIcon(R.drawable.ic_star_border_black).setShowAsAction(MenuItem.SHOW_AS_ACTION_ALWAYS);
        }

        getMenuInflater().inflate(R.menu.main, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {

        int id = item.getItemId();

        if (id == R.id.action_settings) {
            startActivity(new Intent(getBaseContext(), SettingsActivity.class));
        }

        if (id == R.id.logout) {
            SharedPreferences.Editor editor = pref.edit();
            editor.putBoolean(Constants.IS_LOGGED_IN,false);
            editor.putString(Constants.EMAIL,"");
            editor.putString(Constants.NAME,"");
            editor.putString(Constants.UNIQUE_ID,"");
            editor.putString(Constants.AVATAR, "");
            editor.apply();
            startActivity(new Intent(getBaseContext(), LoginActivity.class));
        }

        if(item == shareMenu) {
//            ContentValues values = new ContentValues();
//            values.put(BluetoothShare.URI, "content://" + uritoSend);
//            values.put(BluetoothShare.DESTINATION, deviceAddress);
//            values.put(BluetoothShare.DIRECTION, BluetoothShare.DIRECTION_OUTBOUND);


        }

        if(item == starMenu) {
           new IsStarSelected(bookmark, pref.getString(Constants.ID_GROUP, ""));
            if (isBookmarkSelected == false) {
                starMenu.setIcon(R.drawable.ic_star_black).setShowAsAction(MenuItem.SHOW_AS_ACTION_ALWAYS);
                Toast.makeText(getApplicationContext(), "Added to favorites!",
                        Toast.LENGTH_SHORT).show();
//                FirebaseMessaging.getInstance().unsubscribeFromTopic(pref.getString(Constants.ID_GROUP, ""));

            } else {
                starMenu.setIcon(R.drawable.ic_star_border_black).setShowAsAction(MenuItem.SHOW_AS_ACTION_ALWAYS);
                Toast.makeText(getApplicationContext(), "Removed from favorites!",
                        Toast.LENGTH_SHORT).show();
//                FirebaseMessaging.getInstance().subscribeToTopic(pref.getString(Constants.ID_GROUP, ""));
            }
            }

        return super.onOptionsItemSelected(item);
    }

    @SuppressWarnings("StatementWithEmptyBody")
    @Override
    public boolean onNavigationItemSelected(MenuItem item) {
        // Handle navigation view item clicks here.
        int id = item.getItemId();

        if (id == R.id.groups_nav) {
            MyGroupsFragment tabsFragment = new MyGroupsFragment();
            getSupportFragmentManager().beginTransaction()
                    .replace(R.id.content_frame, tabsFragment)
                    .addToBackStack(null)
                    .commit();
            elevateActionBar(true);

        } else if (id == R.id.change_group_nav) {

            ChangeGroupFragment changeGroupFragment = new ChangeGroupFragment();
            getSupportFragmentManager().beginTransaction()
                    .setCustomAnimations(R.anim.enter,R.anim.exit,R.anim.pop_enter, R.anim.pop_exit)
                    .replace(R.id.content_frame, changeGroupFragment)
                    .addToBackStack(null)
                    .commit();
            elevateActionBar(true);

        } else if (id == R.id.settings_nav) {

            SettingsFragment settingsFragment = new SettingsFragment();
            getSupportFragmentManager().beginTransaction()
                    .setCustomAnimations(R.anim.enter, R.anim.exit, R.anim.pop_enter, R.anim.pop_exit)
                    .replace(R.id.content_frame, settingsFragment)
                    .addToBackStack(null)
                    .commit();
            elevateActionBar(true);
        }

        DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
        drawer.closeDrawer(GravityCompat.START);
        return true;
    }

    public void onBookmarkItemSelected(String email, String id_group, String _nameOfGroup) {

        OkHttpClient.Builder okHttpClient = new OkHttpClient.Builder();

        HttpLoggingInterceptor debugger =
                new HttpLoggingInterceptor()
                        .setLevel(HttpLoggingInterceptor.Level.BODY);
        okHttpClient
                .addInterceptor(debugger);

        Retrofit retrofit = new Retrofit.Builder()
                .baseUrl(Constants.BASE_URL)
                .addConverterFactory(GsonConverterFactory.create())
                .client(okHttpClient.build())
                .build();

        RequestInterface requestInterface = retrofit.create(RequestInterface.class);

        Integer id_int_group = Integer.parseInt(id_group);
        bookmark = new Bookmark(email, id_int_group, _nameOfGroup);

        ServerRequest request = new ServerRequest();
        request.setOperation(Constants.BOOKMARK_OPERATION);
        request.setBookmark(bookmark);

        Call<ServerResponse> response = requestInterface.operation(request);

        response.enqueue(new Callback<ServerResponse>() {

            @Override
            public void onResponse(Call<ServerResponse> call, retrofit2.Response<ServerResponse> response) {

                ServerResponse resp = response.body();
                if (resp.getResult().equals(Constants.SUCCESS))
//                    Log.d(Constants.TAG, "success");
                    isBookmarkSelected = true;

                else
                    isBookmarkSelected = false;

                    if (isBookmarkSelected == true)
                        starMenu.setIcon(R.drawable.ic_star_black).setShowAsAction(MenuItem.SHOW_AS_ACTION_ALWAYS);
                    else
                        starMenu.setIcon(R.drawable.ic_star_border_black).setShowAsAction(MenuItem.SHOW_AS_ACTION_ALWAYS);
            }

            @Override
            public void onFailure(Call<ServerResponse> call, Throwable t) {

//                progress.setVisibility(View.INVISIBLE);
                Log.d(Constants.TAG, "failed", t);
//                Snackbar.make(getView(), t.getLocalizedMessage(), Snackbar.LENGTH_LONG).show();

            }
        });
    }

    private void elevateActionBar(boolean elevate){
        //Elevate ActionBar (make ActionBar have a shadow)
        AppBarLayout appBarLayout = (AppBarLayout) findViewById(R.id.appBar);
        if(elevate) {
            appBarLayout.setElevation(7);
        } else{
            appBarLayout.setElevation(0);
        }
    }

    @Override
    protected void onResume() {
        super.onResume();

        // register GCM registration complete receiver
        LocalBroadcastManager.getInstance(this).registerReceiver(mRegistrationBroadcastReceiver,
                new IntentFilter(Config.REGISTRATION_COMPLETE));

        // register new push message receiver
        // by doing this, the activity will be notified each time a new message arrives
        LocalBroadcastManager.getInstance(this).registerReceiver(mRegistrationBroadcastReceiver,
                new IntentFilter(Config.PUSH_NOTIFICATION));

        // clear the notification area when the app is opened
        NotificationUtils.clearNotifications(getApplicationContext());
    }

    @Override
    protected void onPause() {
        LocalBroadcastManager.getInstance(this).unregisterReceiver(mRegistrationBroadcastReceiver);
        super.onPause();
    }

if you are using ActionBarToggle then add this line to your code.如果您使用的是ActionBarToggle则将此行添加到您的代码中。

ActionBarToggle toggle = new ActionBarToggle(....);

call toggle.setDrawerIndicatorEnabled(false);调用toggle.setDrawerIndicatorEnabled(false); on your ActionBarDrawerToggle在你的 ActionBarDrawerToggle 上

full code which your required to work with actionBarToggle and hamburgerIcon您需要使用 actionBarToggle 和 hamburgerIcon 的完整代码

add this to your MainActivity将此添加到您的 MainActivity

private ActionBarDrawerToggle setupDrawerToggle() {
    ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(this, mDrawer, toolbar, R.string.drawer_open, R.string.drawer_close);
    return toggle;
}

add these lines to your activity onCreate method将这些行添加到您的活动onCreate方法中

// drawer hamburger icons
    drawerToggle = setupDrawerToggle();

    // to disable hamburger icon
    drawerToggle.setDrawerIndicatorEnabled(false);

    // Tie DrawerLayout events to the ActionBarToggle
    mDrawer.addDrawerListener(drawerToggle);

    // Setup drawer view
    setupDrawerContent(nvDrawer);

try this尝试这个

Add this in onCreate .onCreate添加它。

DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
    ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(
                    this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
            drawer.setDrawerListener(toggle);
            toggle.syncState();
            getSupportActionBar().setDisplayHomeAsUpEnabled(true);
            getSupportActionBar().setDefaultDisplayHomeAsUpEnabled(false);
            toggle.setDrawerIndicatorEnabled(false);
            toggle.setHomeAsUpIndicator(null); //or you can add icon
            toggle.setHomeAsUpIndicator(R.id.icon);//add this for custom icon

Credits: https://stackoverflow.com/a/33484267/5962715学分: https : //stackoverflow.com/a/33484267/5962715

In my case, I just needed to set the lock mode to "Locked Closed" and then erase the hamburger icon directly on the toolbar.就我而言,我只需要将锁定模式设置为“锁定关闭”,然后直接在工具栏上删除汉堡图标。 In my case, it wasn`t necessary to show the arrow instead of the hamburger.就我而言,没有必要显示箭头而不是汉堡包。

private fun disableDrawer() {
    val drawerLayout: DrawerLayout = findViewById(R.id.drawer_layout)
    val toolbar: Toolbar = findViewById(R.id.toolbar)
    drawerLayout.setDrawerLockMode(DrawerLayout.LOCK_MODE_LOCKED_CLOSED);
    toolbar.navigationIcon = null
}

To enable again, I just need to unlock the drawer and put the icon there, once I am using navigation controller, it was easier to recreate calling setupActionBarWithNavController.要再次启用,我只需要解锁抽屉并将图标放在那里,一旦我使用导航控制器,重新创建调用 setupActionBarWithNavController 就更容易了。

private fun enableDrawer() {
    val drawerLayout: DrawerLayout = findViewById(R.id.drawer_layout)
    drawerLayout.setDrawerLockMode(DrawerLayout.LOCK_MODE_UNLOCKED)
    val navController = findNavController(R.id.nav_host_fragment)
    setupActionBarWithNavController(navController, appBarConfiguration)
}

As it is suggested in this post https://stackoverflow.com/a/22612901/3922542 you can change the Display property of it in onCreate()正如这篇文章https://stackoverflow.com/a/22612901/3922542 中所建议的,您可以在onCreate()更改它的 Display 属性

getActionBar().setDisplayHomeAsUpEnabled(false);

It will hide the navagation drawer icon.它将隐藏导航抽屉图标。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM