我有一個Actionbar
從android.support.v7.widget.Toolbar
。它帶有動畫的漢堡包圖像,用於後退箭頭,我想將後退箭頭從<更改爲 - >。我如何在Android Studio中執行此操作?使用appcompat-v7更改Actionbar中的後退箭頭圖像
我讀了一個地方用setHomeAsUpIndicator()
方法改變它,但它改變了漢堡包按鈕,它沒有動畫來回退箭頭。
我有一個Actionbar
從android.support.v7.widget.Toolbar
。它帶有動畫的漢堡包圖像,用於後退箭頭,我想將後退箭頭從<更改爲 - >。我如何在Android Studio中執行此操作?使用appcompat-v7更改Actionbar中的後退箭頭圖像
我讀了一個地方用setHomeAsUpIndicator()
方法改變它,但它改變了漢堡包按鈕,它沒有動畫來回退箭頭。
至少有半打的方法可以做到這一點,但可能是最簡單和最短的是使用反射來抓住ActionBarDrawerToggle
的Drawable
,並翻轉其方向。
本示例將該功能包裝在一個子類中,無論您的設置如何(只要原始類在那裏工作),都應該可以正常工作。
public class FlippedDrawerToggle extends ActionBarDrawerToggle {
public FlippedDrawerToggle(Activity activity, DrawerLayout drawerLayout,
int openDrawerContentDescRes, int closeDrawerContentDescRes) {
this(activity, drawerLayout, null,
openDrawerContentDescRes, closeDrawerContentDescRes);
}
public FlippedDrawerToggle(Activity activity, DrawerLayout drawerLayout,
Toolbar toolbar, int openDrawerContentDescRes, int closeDrawerContentDescRes) {
super(activity, drawerLayout, toolbar,
openDrawerContentDescRes, closeDrawerContentDescRes);
try {
Field sliderField = ActionBarDrawerToggle.class.getDeclaredField("mSlider");
sliderField.setAccessible(true);
DrawerArrowDrawable arrow = (DrawerArrowDrawable) sliderField.get(this);
arrow.setDirection(DrawerArrowDrawable.ARROW_DIRECTION_RIGHT);
}
catch (NoSuchFieldException | IllegalAccessException e) {
// Fail silently
}
}
}
這隻會改變切換圖像的方向。如果您實際上希望翻轉整個ActionBar
/Toolbar
,則應相應地更改佈局的方向。
試試這個:
//Find the action bar for customizations
final ActionBar ab = getSupportActionBar();
assert ab != null;
//Make the action bar display an up arrow and set its drawable and color
ab.setDisplayHomeAsUpEnabled(true);
final Drawable upArrow = ResourcesCompat.getDrawable(
getResources(),
R.drawable.abc_ic_ab_back_mtrl_am_alpha, //this is the <- arrow from android resources. Change this to the thing you want.
null);
assert upArrow != null;
upArrow.setColorFilter(
ContextCompat.getColor(
getApplicationContext(),
R.color.white // change this to the color you want (or remove the setColorFilter call)
),
PorterDuff.Mode.SRC_ATOP);
ab.setHomeAsUpIndicator(upArrow);
我說,在我的問題,我測試了'setHomeAsUpIndicator'。但它刪除動畫,它只是改變漢堡包形象 – Maryam
mDrawerToggle = new ActionBarDrawerToggle...
和mDrawerToggle.syncState();
之間添加這個條件是這樣的:
mDrawerToggle = new ActionBarDrawerToggle(this, mDrawerLayout, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
if (getResources().getConfiguration().getLayoutDirection() == View.LAYOUT_DIRECTION_RTL)
{
toolbar.setLayoutDirection(View.LAYOUT_DIRECTION_RTL);
}
mDrawerToggle.syncState();
的圖像可視化將有所助益 –