2016-06-12 48 views
3

我有一個Actionbarandroid.support.v7.widget.Toolbar。它帶有動畫的漢堡包圖像,用於後退箭頭,我想將後退箭頭從<更改爲 - >。我如何在Android Studio中執行此操作?使用appcompat-v7更改Actionbar中的後退箭頭圖像

我讀了一個地方用setHomeAsUpIndicator()方法改變它,但它改變了漢堡包按鈕,它沒有動畫來回退箭頭。

+1

的圖像可視化將有所助益 –

回答

2

至少有半打的方法可以做到這一點,但可能是最簡單和最短的是使用反射來抓住ActionBarDrawerToggleDrawable,並翻轉其方向。

本示例將該功能包裝在一個子類中,無論您的設置如何(只要原始類在那裏工作),都應該可以正常工作。

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,則應相應地更改佈局的方向。

+0

非常感謝你:) – Maryam

+0

沒問題。如果你沒有注意到,自從我最初發布它以來,我在代碼中改變了一些東西。我忘記了帶有「工具欄」的構造函數,我使用的方向常量僅在19+以上。我認爲現在應該很好。乾杯! –

+0

另一個問題:你知道如何設置'layoutdirection'爲'RTL'的API級別低於17?因爲現在漢堡包圖像位於操作欄左側 – Maryam

0

試試這個:

//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); 
+0

我說,在我的問題,我測試了'setHomeAsUpIndicator'。但它刪除動畫,它只是改變漢堡包形象 – Maryam

0

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