2015-12-10 17 views
5

自分で作成したいActionBarレイアウト。 (例えばペイントで作成した)このようAndroidのカスタムActionBarボタンでアップナビゲーションプロパティを追加

enter image description here

は、それが第二ボタンアップのナビゲーションプロパティを与えることは可能ですか?だから私はそれを押すと、それはこのActivityを終了し、それは親です。

Navigation Drawerのバーガーアイコン、アップナビゲーションのアップアイコン、およびアクティビティのタイトルを持っています。

可能ですか?または既に解決策がありますか?

答えて

1

実際、これはかなり簡単です(少しハッキリですが)。 まず、好ましくは(バックボタンの描画可能作成 - セレクタとして、プレス/正常状態を区別する:

<?xml version="1.0" encoding="utf-8"?> 
<selector xmlns:android="http://schemas.android.com/apk/res/android"> 
    <item android:state_pressed="true" android:drawable="@drawable/back_button_pressed"/> 
    <item android:drawable="@drawable/back_button"/> 
</selector> 

次に、ツールバーtoolbar.setLogo(R.drawable.back_button_selector);

のロゴ唯一この描画可能な設定。左が(感謝ニコラのポストhere)を

View logoView = getToolbarLogoIcon(toolbar); 
logoView.setOnClickListener(new View.OnClickListener() { 
    @Override 
    public void onClick(View v) { 
     onBackPressed(); 
    } 
}); 

... 

private View getToolbarLogoIcon(Toolbar toolbar){ 
    //check if contentDescription previously was set 
    boolean hadContentDescription = android.text.TextUtils.isEmpty(toolbar.getLogoDescription()); 
    String contentDescription = String.valueOf(!hadContentDescription ? toolbar.getLogoDescription() : "logoContentDescription"); 
    toolbar.setLogoDescription(contentDescription); 
    ArrayList<View> potentialViews = new ArrayList<>(); 

    //find the view based on it's content description, set programatically or with android:contentDescription 
    toolbar.findViewsWithText(potentialViews,contentDescription, View.FIND_VIEWS_WITH_CONTENT_DESCRIPTION); 

    //Nav icon is always instantiated at this point because calling setLogoDescription ensures its existence 
    View logoIcon = null; 
    if (potentialViews.size() > 0) { 
     logoIcon = potentialViews.get(0); 
    } 

    //Clear content description if not previously present 
    if (hadContentDescription) { 
     toolbar.setLogoDescription(null); 
    } 

    return logoIcon; 
} 

クリックリスナーを設定する場合、またはあなたが反射を怖がっていない場合、それは簡単に次のように行うことができます。

try { 
     Field declaredField = toolbar.getClass().getDeclaredField("mLogoView"); 
     declaredField.setAccessible(true); 
     View logoView = (View) declaredField.get(toolbar); 
     logoView.setOnClickListener(new View.OnClickListener() { 
      @Override 
      public void onClick(View v) { 
       onBackPressed(); 
      } 
     }); 
    } catch (Exception ex) { 
     //error 
    } 

カスタムレイアウトをActionBarに設定することもできます。 ナビゲーション・ドロワーがセカンダリー・アクティビティーで不可欠な場合は、UI/UXのガイドラインに従って再チェックすることを推奨します。

+0

ありがとうございます!出来た! – raymondis

関連する問題