Иконка панели инструментов
Я ищу способ отобразить значок гамбургера без использования Drawer/DrawerToggle и использовать значок по умолчанию, включенный в Android
![enter image description here]()
Установив getSupportActionBar().setDisplayHomeAsUpEnabled(true);
, отобразится стрелка назад, но не гамбургер. Другое сообщение в Stackoverflow (например, this или this) использует DrawerLayout или пользовательский drawable. Я не могу найти вектор или png для значка гамбургера в Android-источнике.
Знаете ли вы, как я могу найти оригинальный значок гамбургера в библиотеке android/support? (или как его отображать)
Примечание. Вектор и png можно найти на сайте google.com/design: http://www.google.com/design/spec/resources/sticker-sheets-icons.html#
В моей деятельности
mToolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(mToolbar);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setHomeButtonEnabled(true);
mToolbar.setNavigationOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Log.d(LOG_TAG, "navigation clicked");
}
});
Файл макета
<android.support.v7.widget.Toolbar
android:id="@+id/toolbar"
android:layout_height="wrap_content"
android:layout_width="match_parent"
android:minHeight="?attr/actionBarSize"
android:background="?attr/colorPrimary"
app:theme="@style/ThemeOverlay.AppCompat.ActionBar"/>
Styles.xml
<!-- Base application theme. -->
<style name="Theme.AppTheme" parent="Theme.AppCompat.Light.NoActionBar">
<item name="colorPrimary">@color/primaryDef</item>
<item name="colorPrimaryDark">@color/primaryDarkDef</item>
<item name="colorAccent">@color/primaryDef</item>
<!-- Remove the actionbar shadow-->
<item name="android:windowContentOverlay">@null</item>
</style>
Ответы
Ответ 1
Если вы хотите использовать тот же самый ящик, что и леденец, тогда позвольте мне сказать вам, что это не статическое изображение. Это изображение рисуется в реальном времени классом под названием DrawerArrowDrawableToggle
. Таким образом, для этого нет значка "гамбургер".
Однако, если вы хотите значок гамбургера без анимации, вы можете найти его здесь:
http://shreyasachar.com/AndroidAssetStudio
Вы также можете использовать http://www.google.com/design/spec/resources/sticker-sheets-icons.html#sticker-sheets-icons-components и загрузить пакет. Значок навигации имеет имя ic_menu
и расположен в папке navigation
:
https://github.com/google/material-design-icons/blob/master/navigation/drawable-xxxhdpi/ic_menu_grey600_48dp.png
![enter image description here]()
Ответ 2
Чтобы иметь анимированный значок гамбургера, вы должны использовать DrawerLayout
с ActionBarDrawerToggle
и включить значок для ActionBar
и для ActionBarDrawerToggle
.
Пример:
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
DrawerLayout drawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
ActionBarDrawerToggle mDrawerToggle;
setSupportActionBar(toolbar);
final ActionBar actionBar = getSupportActionBar();
if (actionBar != null)
{
actionBar.setDisplayHomeAsUpEnabled(true);
mDrawerToggle = new ActionBarDrawerToggle(this, drawerLayout, toolbar, R.string.hello_world, R.string.hello_world)
{
public void onDrawerClosed(View view)
{
supportInvalidateOptionsMenu();
//drawerOpened = false;
}
public void onDrawerOpened(View drawerView)
{
supportInvalidateOptionsMenu();
//drawerOpened = true;
}
};
mDrawerToggle.setDrawerIndicatorEnabled(true);
drawerLayout.setDrawerListener(mDrawerToggle);
mDrawerToggle.syncState();
}
Кроме того, вам необходимо добавить эти методы в свою активность:
@Override
protected void onPostCreate(Bundle savedInstanceState)
{
super.onPostCreate(savedInstanceState);
mDrawerToggle.syncState();
}
@Override
public void onConfigurationChanged(Configuration newConfig)
{
super.onConfigurationChanged(newConfig);
mDrawerToggle.onConfigurationChanged(newConfig);
}
Ответ 3
У меня была та же проблема, и я нашел простейшее решение здесь:
appcompatv7-v21-navigation-drawer-not-showing-hamburger-icon
Все, что мне нужно было сделать, это позвонить:
mDrawerToggle.syncState();
Ответ 4
Вот простейшее решение, которое сработало для меня.
ActionBarDrawerToggle
имеет два типа конструкторов. Один из них принимает панель инструментов в качестве параметра. Используйте это (второе ниже), чтобы получить анимированный гамбургер.
ActionBarDrawerToggle(this, mDrawerLayout, R.string.content_desc_drawer_open,
R.string.content_desc_drawer_close);
ActionBarDrawerToggle(this, mDrawerLayout, toolbar, R.string.content_desc_drawer_open,
R.string.content_desc_drawer_close);` //use this constructor
Ответ 5
ok, чтобы скрывать использование стрелок назад
getSupportActionBar().setDisplayHomeAsUpEnabled(false);
getSupportActionBar().setHomeButtonEnabled(false);
затем найдите значок гамбургера в Интернете → гамбургер
и, наконец, установите этот drawable в вашем проекте с помощью метода действий:
getSupportActionBar().setLogo(R.drawable.hamburger_icon);
Ответ 6
У меня была та же проблема.
Получите ToolBar
, а затем установите значок навигации
final android.support.v7.widget.Toolbar toolbar = (android.support.v7.widget.Toolbar) findViewById(R.id.toolbar);
toolbar.setNavigationIcon(R.drawable.blablabla);
Ответ 7
Toolbar mToolbar = (Toolbar) findViewById(R.id.toolbar);
mToolbar.setTitle("title");
setSupportActionBar(mToolbar);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setHomeButtonEnabled(true);
getSupportActionBar().setHomeAsUpIndicator(R.drawable.ic_list);
Ответ 8
Для этого вам просто нужно написать несколько строк
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.setDrawerIndicatorEnabled(true);
toggle.syncState();
toggle.setDrawerIndicatorEnabled(true);, если это false, делает это true или удаляет эту строку
Ответ 9
Возможно, вы можете попробовать это, но вы потеряете анимацию между стрелкой и значком гамбургера
@Override
protected void onCreate(Bundle arg0) {
super.onCreate(arg0);
super.setContentView(R.layout.activity_menu_drawer_left);
_drawerToggle = new ActionBarDrawerToggle(this, _drawerLayout, R.string.drawer_opened, R.string.drawer_closed) {
public void onDrawerOpened(View drawerView) {
super.onDrawerOpened(drawerView);
changeDrawerIconOnDrawerClick(R.drawable.abc_ic_ab_back_mtrl_am_alpha);
}
/** Called when a drawer has settled in a completely closed state. */
public void onDrawerClosed(View view) {
super.onDrawerClosed(view);
changeDrawerIconOnDrawerClick(R.drawable.ic_drawer);
}
};
//to change default icon to hamburger item initially
changeDrawerIconOnDrawerClick(R.drawable.ic_drawer); }
private void changeDrawerIconOnDrawerClick(int resourceId) {
//Drawable icon = ContextCompat.getDrawable(getApplicationContext(), resourceId);
Drawable icon = ResourcesCompat.getDrawable(getResources(), resourceId, null);
icon.setColorFilter(getResources().getColor(R.color.white), PorterDuff.Mode.SRC_ATOP);
_drawerToggle.setDrawerIndicatorEnabled(false);
_drawerToggle.setHomeAsUpIndicator(icon);
}
Ответ 10
Вы можете попытаться сделать свой собственный рисунок для значка гамбургера таким образом.
<vector xmlns:android="http://schemas.android.com/apk/res/android"
android:width="24dp"
android:height="24dp"
android:viewportHeight="24.0"
android:viewportWidth="24.0">
<path
android:fillColor="#ffffff"
android:pathData="M3,18h18v-2L3,16v2zM3,13h18v-2L3,11v2zM3,6v2h18L21,6L3,6z" />
</vector>
Затем в вашем фрагменте/активности
getSupportActionBar().setHomeAsUpIndicator(R.drawable.as_above);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
Для других чертежей это может помочь: https://github.com/google/material-design-icons/blob/master/navigation/drawable-anydpi-v21/
Ответ 11
Замените стрелку вверх по умолчанию на свой собственный
getSupportActionBar().setHomeAsUpIndicator(R.drawable.hamburger);
Ответ 12
Просто добавьте следующее в свой метод onCreate,
if (getSupportActionBar() != null) {
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setHomeButtonEnabled(true);
}
ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(
this, mDrawer, mToolbar, R.string.home_navigation_drawer_open, R.string.home_navigation_drawer_close) {
public void onDrawerClosed(View view) {
super.onDrawerClosed(view);
invalidateOptionsMenu();
}
public void onDrawerOpened(View drawerView) {
super.onDrawerOpened(drawerView);
invalidateOptionsMenu();
}
@Override
public void onDrawerSlide(View drawerView, float slideOffset) {
super.onDrawerSlide(drawerView, slideOffset);
}
};
mDrawer.addDrawerListener(toggle);
toggle.syncState();
и In strings.xml,
<string name="home_navigation_drawer_open">Open navigation drawer</string>
<string name="home_navigation_drawer_close">Close navigation drawer</string>
Ответ 13
Используйте этот конструктор в MyActionBarDrawerToggle:
public MyActionBarDrawerToggle(AppCompatActivity host, DrawerLayout drawerlayout, SupportToolbar toolbar, int openedResource, int closedResource)
: base(host, drawerlayout, toolbar, openedResource, closedResource)
{
mHostActivity = host;
mOpenedResource = openedResource;
mClosedResource = closedResource;
}
и вызовите этот метод в mainActivity (с помощью AppCompatActivity)
mDrawerToggle = new MyActionBarDrawerToggle(
this, //Host Activity
mDrawerLayout, //DrawerLayout
mToolbar, //Toolbar
Resource.String.openDrawer, //Opened Message
Resource.String.closeDrawer //Closed Message
);
mDrawerLayout.AddDrawerListener(mDrawerToggle);
SupportActionBar.SetHomeButtonEnabled(true);
SupportActionBar.SetDisplayShowTitleEnabled(true);
mDrawerToggle.DrawerIndicatorEnabled = true;
mDrawerToggle.SyncState();
Ответ 14
в onCreate()
:
setSupportActionBar(toolbar);
ActionBar actionBar = getSupportActionBar();
drawerToggle = new ActionBarDrawerToggle(this, drawerLayout, toolbar, R.string.open, R.string.close) {
@Override
public void onDrawerClosed(View drawerView) {
super.onDrawerClosed(drawerView);
supportInvalidateOptionsMenu();
}
@Override
public void onDrawerOpened(View drawerView) {
super.onDrawerOpened(drawerView);
supportInvalidateOptionsMenu();
}
};
drawerLayout.setDrawerListener(drawerToggle);
drawerToggle.setToolbarNavigationClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Backstack.get(MainActivity.this).goBack();
}
});
//actionBar.setHomeAsUpIndicator(R.drawable.ic_menu);
//getSupportActionBar().setDisplayHomeAsUpEnabled(false);
actionBar.setDisplayHomeAsUpEnabled(false);
actionBar.setHomeButtonEnabled(true);
И при настройке навигации вверх:
private void setupViewsForKey(Key key) {
if(key.shouldShowUp()) {
drawerToggle.setDrawerIndicatorEnabled(false);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
}
else {
getSupportActionBar().setDisplayHomeAsUpEnabled(false);
drawerToggle.setDrawerIndicatorEnabled(true);
}
drawerToggle.syncState();