Android appcompat v7 21 라이브러리에서 DrawerArrowToggle을 구현하는 방법


97

이제 Android 5.0이 출시되었으므로 애니메이션 작업 표시 줄 아이콘을 구현하는 방법이 궁금합니다.

이 라이브러리는 여기 구현은 나를 위해 미세하지만 APPCOMPAT V7 라이브러리 이후는 어떻게이 구현 될 수있다?

라이브러리는 themes.xml에서이를 참조합니다.

 <item name="drawerArrowStyle">@style/Widget.AppCompat.DrawerArrowToggle</item>

이 스타일로

 <style name="Base.V7.Theme.AppCompat" parent="Platform.AppCompat">

최신 정보

v7 DrawerToggle을 사용하여 구현했습니다. 그러나 나는 그것을 스타일링 할 수 없습니다. 도와주세요

v7 styles_base.xml에서 스타일을 찾았습니다.

<style name="Base.Widget.AppCompat.DrawerArrowToggle" parent="">
    <item name="color">?android:attr/textColorSecondary</item>
    <item name="thickness">2dp</item>
    <item name="barSize">18dp</item>
    <item name="gapBetweenBars">3dp</item>
    <item name="topBottomBarArrowSize">11.31dp</item>
    <item name="middleBarArrowSize">16dp</item>
    <item name="drawableSize">24dp</item>
    <item name="spinBars">true</item>
</style>

나는 이것을 내 스타일에 추가했지만 작동하지 않았습니다. 내 attr.xml에도 추가되었습니다.

<declare-styleable name="DrawerArrowToggle">
    <!-- The drawing color for the bars -->
    <attr name="color" format="color"/>
    <!-- Whether bars should rotate or not during transition -->
    <attr name="spinBars" format="boolean"/>
    <!-- The total size of the drawable -->
    <attr name="drawableSize" format="dimension"/>
    <!-- The max gap between the bars when they are parallel to each other -->
    <attr name="gapBetweenBars" format="dimension"/>
    <!-- The size of the top and bottom bars when they merge to the middle bar to form an arrow -->
    <attr name="topBottomBarArrowSize" format="dimension"/>
    <!-- The size of the middle bar when top and bottom bars merge into middle bar to form an arrow -->
    <attr name="middleBarArrowSize" format="dimension"/>
    <!-- The size of the bars when they are parallel to each other -->
    <attr name="barSize" format="dimension"/>
    <!-- The thickness (stroke size) for the bar paint -->
    <attr name="thickness" format="dimension"/>
</declare-styleable>

그러나 그렇게 할 때 충돌하고 색상 유형 오류가 표시됩니다. 내가 무엇을 놓치고 있습니까?

답변:


243

첫째, 이제 android.support.v4.app.ActionBarDrawerToggle가 더 이상 사용되지 않음을 알아야합니다 .

이를 android.support.v7.app.ActionBarDrawerToggle.

여기 내 예를 들어 내가 새를 사용 Toolbar를 교체 ActionBar.

MainActivity.java

public class MainActivity extends ActionBarActivity {
    @Override
    protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    Toolbar mToolbar = (Toolbar) findViewById(R.id.toolbar);
    setSupportActionBar(mToolbar);
    DrawerLayout mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
    ActionBarDrawerToggle mDrawerToggle = new ActionBarDrawerToggle(
        this,  mDrawerLayout, mToolbar,
        R.string.navigation_drawer_open, R.string.navigation_drawer_close
    );
    mDrawerLayout.setDrawerListener(mDrawerToggle);
    getSupportActionBar().setDisplayHomeAsUpEnabled(true);
    getSupportActionBar().setHomeButtonEnabled(true);
    mDrawerToggle.syncState();
}

styles.xml

<style name="AppTheme" parent="Theme.AppCompat.Light">
    <item name="drawerArrowStyle">@style/DrawerArrowStyle</item>
</style>

<style name="DrawerArrowStyle" parent="Widget.AppCompat.DrawerArrowToggle">
    <item name="spinBars">true</item>
    <item name="color">@android:color/white</item>
</style>

AndroidDocument # DrawerArrowToggle_spinBars 에서 문서를 읽을 수 있습니다.

이 속성은 메뉴-화살표 애니메이션을 구현하는 키입니다.

public static int DrawerArrowToggle_spinBars

전환하는 동안 막대가 회전 해야하는지 여부
"true"또는 "false"의 부울 값이어야합니다.

그래서 이것을 설정합니다 : <item name="spinBars">true</item>.

그런 다음 애니메이션을 표시 할 수 있습니다.

이것이 당신을 도울 수 있기를 바랍니다.


12
햄버거 아이콘이 표시되는 데 문제가 발생했습니다. 전화로 해결 mDrawerToggle.syncState();했습니다.
— aheuermann 2014

1
나를 위해 getSupportActionBar () null을 반환합니다. 그 이유는 무엇입니까?
— Ramesh_D

2
Android Studio는 Cannot resolve method setSupportActionBar(android.widget.Toolbar). 나는 또한 android.support.v7.toolbar. 왜 이런 일이 발생하는지 아는 사람이 있습니까?
— pez

1
사용 setSupportActionBar(mToolbar);하고 정의 <item name="spinBars">true</item>했지만 애니메이션이 작동하지 않음
— SweetWisher ツ

2
툴바를 활동의 ActionBar로 설정하는 경우 ActionBarDrawerToggle (Activity, DrawerLayout, int, int)을 사용해야합니다.
— Peter Zhao

24

탐색 창 만들기 교육 에서 제안한대로 지원 라이브러리에서 제공하는 DrawerLayout 을 사용하는 경우 새로 추가 된 android.support를 사용할 수 있습니다 . v7 .app.ActionBarDrawerToggle (참고 : 현재 지원 중단 된 android.support. v4 .app.ActionBarDrawerToggle과 다름 ) :

서랍이 닫히면 햄버거 아이콘이 표시되고 서랍이 열리면 화살표가 표시됩니다. 서랍이 열리면이 두 상태간에 애니메이션이 적용됩니다.

교육이 deprecation / new 클래스를 고려하도록 업데이트되지는 않았지만 거의 똑같은 코드를 사용할 수 있어야합니다. 구현에서 유일한 차이점은 생성자입니다.


내 앱에서 v4를 사용하고 있습니다. api 15 이전의 장치를 지원할 필요가 없습니다.이 기능을 사용하려면 v7 작업 표시 줄 서랍 토글을 사용해야합니까? 그렇게했다면 내 모든 스타일을 AppCompat으로 변환하고 활동을 작업 표시 줄 활동으로 분할하지 않아도됩니까? 또는 v7에서 Drawer 토글 만 구현할 수 있습니다. 지금은 카드보기에 v7을 사용합니다. 15 미만의 API를 지원하지 않는 경우에도 v4를 사용해야합니까? 그리고 카드 뷰에는 v7이 필요하다고 생각합니다.
— Bignadad

머티리얼 디자인에 대한 모든 지원 라이브러리 호환성은 v7-appcompat에서 구현되며 <5.0 장치에서 해당 스타일을 지원하려는 경우 권장됩니다. AppCompat는 v4를 기반으로 구축되어 있으므로 AppCompat를 사용하려는 경우 실제로 결정됩니다. 이미 FragmentActivity를 사용하고 있다면 이미 거의 비슷합니다. 스타일링의 차이는 현재 매우 작습니다 (대부분 android : 속성을 네임 스페이스가 아닌 속성으로 대체).
— ianhanniballake

당신이보고하십시오 복용 상관 없어 경우에 질문을 업데이트
— Bignadad

스타일링에 대한 완전히 별개의 질문입니다. 해당 부분을 다른 질문으로 제출하는 것이 좋습니다 (링크가있는 의견을 자유롭게 추가 할 수 있음).
— ianhanniballake

1
@mraviator-yep : XML을 변경 한 다음 v7을 만들고 첨부합니다 ActionBarDrawerToggle. 정규 대답 APPCOMPAT의 메이커에서 당신의 XML이 구조화되는 방식을 전체 예제를 가지고있다.
— ianhanniballake

17

비슷한 기능을 가진 작은 응용 프로그램을 만들었습니다.

주요 활동

public class MyActivity extends ActionBarActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_my);

        DrawerLayout drawerLayout = (DrawerLayout) findViewById(R.id.drawer);
        android.support.v7.widget.Toolbar toolbar = (android.support.v7.widget.Toolbar) findViewById(R.id.toolbar);
        ActionBarDrawerToggle actionBarDrawerToggle = new ActionBarDrawerToggle(
                this,
                drawerLayout,
                toolbar,
                R.string.open,
                R.string.close
        )

        {
            public void onDrawerClosed(View view)
            {
                super.onDrawerClosed(view);
                invalidateOptionsMenu();
                syncState();
            }

            public void onDrawerOpened(View drawerView)
            {
                super.onDrawerOpened(drawerView);
                invalidateOptionsMenu();
                syncState();
            }
        };
        drawerLayout.setDrawerListener(actionBarDrawerToggle);

        //Set the custom toolbar
        if (toolbar != null){
            setSupportActionBar(toolbar);
        }

        getSupportActionBar().setDisplayHomeAsUpEnabled(true);

        actionBarDrawerToggle.syncState();
    }
}

해당 활동의 내 XML

<android.support.v4.widget.DrawerLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MyActivity"
    android:id="@+id/drawer"
    >

    <!-- The main content view -->
    <FrameLayout
        android:id="@+id/content_frame"
        android:layout_width="match_parent"
        android:layout_height="match_parent" >
        <include layout="@layout/toolbar_custom"/>
    </FrameLayout>
    <!-- The navigation drawer -->
    <ListView
        android:layout_marginTop="?attr/actionBarSize"
        android:id="@+id/left_drawer"
        android:layout_width="240dp"
        android:layout_height="match_parent"
        android:layout_gravity="start"
        android:choiceMode="singleChoice"
        android:divider="@android:color/transparent"
        android:dividerHeight="0dp"
        android:background="#457C50"/>


</android.support.v4.widget.DrawerLayout>

내 사용자 정의 도구 모음 XML

<?xml version="1.0" encoding="utf-8"?>

<android.support.v7.widget.Toolbar
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:id="@+id/toolbar"
    android:background="?attr/colorPrimaryDark">
    <TextView android:text="U titel"
        android:textAppearance="@android:style/TextAppearance.Theme"
        android:textColor="@android:color/white"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        />
</android.support.v7.widget.Toolbar>

내 테마 스타일

<resources>
    <style name="AppTheme" parent="Base.Theme.AppCompat"/>

    <style name="AppTheme.Base" parent="Theme.AppCompat">
        <item name="colorPrimary">@color/primary</item>
        <item name="colorPrimaryDark">@color/primaryDarker</item>
        <item name="android:windowNoTitle">true</item>
        <item name="windowActionBar">false</item>
        <item name="drawerArrowStyle">@style/DrawerArrowStyle</item>
    </style>

    <style name="DrawerArrowStyle" parent="Widget.AppCompat.DrawerArrowToggle">
        <item name="spinBars">true</item>
        <item name="color">@android:color/white</item>
    </style>

    <color name="primary">#457C50</color>
    <color name="primaryDarker">#580C0C</color>
</resources>

가치 -v21의 내 스타일

<?xml version="1.0" encoding="utf-8"?>
<resources>
    <style name="AppTheme" parent="AppTheme.Base">
        <item name="android:windowContentTransitions">true</item>
        <item name="android:windowAllowEnterTransitionOverlap">true</item>
        <item name="android:windowAllowReturnTransitionOverlap">true</item>
        <item name="android:windowSharedElementEnterTransition">@android:transition/move</item>
        <item name="android:windowSharedElementExitTransition">@android:transition/move</item>
    </style>
</resources>

1
이것은 완벽하게 작동하지만 Title을 사용하고 싶지 않으므로 어떻게 처리 할 수 ​​있습니까? 내가 Theme.AppCompat.Light.NoActionBar를 사용하면 getSupportActionBar
— SweetWisher ツ

위의 코드를 사용했습니다. 예외가 발생했습니다.이 활동에는 이미 setsupportactionbar (toolbar) 행의 창 장식에서 제공하는 작업 표시 줄이 있습니다. 나는 getSupportActionBar (). hide (); setContentView (R.layout.activity_main); 이전 이제 작동합니다.
— Thirumalvalavan

setSupportActionBar (도구 모음); 또한 댓글을 달았습니다.
— Thirumalvalavan

9

질문의 업데이트 된 부분에 답하려면 서랍 아이콘 / 화살표의 스타일을 지정하려면 두 가지 옵션이 있습니다.

화살표 자체 스타일 지정

이렇게하려면 다음 drawerArrowStyle과 같이 테마를 재정의 합니다.

<style name="AppBaseTheme" parent="Theme.AppCompat.Light">
    <item name="drawerArrowStyle">@style/MyTheme.DrawerArrowToggle</item>
</style>
<style name="MyTheme.DrawerArrowToggle" parent="Widget.AppCompat.DrawerArrowToggle">
    <item name="color">@android:color/holo_purple</item>
    <!-- ^ this will make the icon purple -->
</style>

ActionBar 자체가 화살표와 일관된 스타일을 가져야하기 때문에 이것은 아마도 원하는 것이 아닐 것입니다 . 따라서 아마도 두 번째 옵션이 필요합니다.

ActionBar / Toolbar 테마

전역 애플리케이션 테마 의 android:actionBarTheme( actionBarThemefor appcompat) 속성을 다음과 같이 고유 한 테마 (에서 파생해야 함)로 재정의합니다 ThemeOverlay.Material.ActionBar/ThemeOverlay.AppCompat.ActionBar.

<style name="AppBaseTheme" parent="Theme.AppCompat.Light">
    <item name="actionBarTheme">@style/MyTheme.ActionBar</item>
</style>
<style name="MyTheme.ActionBar" parent="ThemeOverlay.AppCompat.ActionBar">
    <item name="android:textColorPrimary">@android:color/white</item>
    <!-- ^ this will make text and arrow white -->
    <!-- you can also override drawerArrowStyle here -->
</style>

중요한 점은 여기에 사용자 정의 레이아웃을 사용하는 경우이다 Toolbar(당신이 사용하는 경우 예를 대신 재고의 액션 바의 구현 DrawerLayout- NavigationView- Toolbar는이 반투명 상태 표시 줄에서 볼의 재질 스타일의 서랍 효과를 얻을 콤보를) actionBarTheme속성이 obviosly 아니다 자동으로 선택되므로 ( AppCompatActivity기본값 은에 의해 처리되기 때문에 ActionBar) 사용자 정의의 Toolbar경우 수동으로 테마를 적용하는 것을 잊지 마십시오.

<!--inside your custom layout with DrawerLayout
and NavigationView or whatever -->
<android.support.v7.widget.Toolbar
        ...
        app:theme="?actionBarTheme">

-이것은 AppCompat의 기본값 ThemeOverlay.AppCompat.ActionBar또는 파생 된 테마에 속성을 설정 한 경우 재정의로 확인됩니다.

추신 : drawerArrowStyle재정의 및 spinBars속성 에 대한 약간의 의견 -많은 출처 true가 서랍 / 화살표 애니메이션을 얻으려면 설정해야한다고 제안합니다 . 것이며, spinBars그것이 true 기본적으로 (아웃 확인 APPCOMPAT의 Base.Widget.AppCompat.DrawerArrowToggle.Common스타일)를 재정의 할 필요가 없습니다 actionBarTheme애니메이션 작업을 얻을 전혀. 애니메이션을 재정의하고 속성을로 설정해도 애니메이션을 얻을 수 있습니다 false. 여기서 중요한 ActionBarDrawerToggle것은를 사용하는 것입니다. 멋진 애니메이션 드로어 블을 가져 오는 것입니다.


2

위의 코드를 조금 수정하고 싶습니다.

    public class MainActivity extends ActionBarActivity {
        @Override
        protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        Toolbar mToolbar = (Toolbar) findViewById(R.id.toolbar);
        DrawerLayout mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
        ActionBarDrawerToggle mDrawerToggle = new ActionBarDrawerToggle(
            this,  mDrawerLayout, mToolbar,
            R.string.navigation_drawer_open, R.string.navigation_drawer_close
        );
        mDrawerLayout.setDrawerListener(mDrawerToggle);

        getSupportActionBar().setDisplayHomeAsUpEnabled(true);
        getSupportActionBar().setHomeButtonEnabled(true);
    }

다른 모든 것은 동일하게 유지됩니다 ...

Drawerlayout툴바 오버레이에 문제가있는 분들을 위해

android:layout_marginTop="?attr/actionBarSize"서랍 내용의 루트 레이아웃에 추가


getSupportActionBar()그냥 연장 할 때 어떻게 사용 Activity합니까?
— wzieba

단순히 당신, 당신은에서 확장 할 필요가 없습니다ActionBarActivity
— 니틴 Misra는
당사 사이트를 사용함과 동시에 당사의 쿠키 정책과 개인정보 보호정책을 읽고 이해하였음을 인정하는 것으로 간주합니다.
Licensed under cc by-sa 3.0 with attribution required.