> Java > java지도 시간 > Android는 DrawerLayout을 사용하여 QQ와 같은 양방향 슬라이딩 메뉴를 구현합니다.

Android는 DrawerLayout을 사용하여 QQ와 같은 양방향 슬라이딩 메뉴를 구현합니다.

高洛峰
풀어 주다: 2017-01-07 14:42:09
원래의
1423명이 탐색했습니다.

1. 개요

이전에 QQ5.2에 오른쪽 메뉴가 추가되는 것과 동시에 안드로이드 수준의 모방 QQ5.0 사이드 슬라이딩 메뉴 효과 사용자 정의 컨트롤을 작성했습니다. DrawerLayout을 읽은 후 공식적인 내용에 더 관심이 생기고 다른 한편으로는 이 기능이 사용하기 정말 편리해서 QQ5.2 양방향을 많이 모방한 데모를 작성했습니다. 사이드 슬라이딩, 모두와 공유.

먼저 렌더링을 살펴보세요:

Android는 DrawerLayout을 사용하여 QQ와 같은 양방향 슬라이딩 메뉴를 구현합니다.

DrawerLayout은 사용하기 정말 편리합니다~

2. DrawerLayout DrawerLayout을 루트 레이아웃으로 직접 사용하려면

을 사용하고 그 안의 첫 번째 View는 콘텐츠 영역, 두 번째 View는 왼쪽 메뉴, 세 번째 View는 오른쪽이 됩니다. 현재 슬라이딩 메뉴는 선택사항입니다.

첫 번째 View의 너비와 높이는 match_parent로 설정되어야 하며 이는 당연합니다.

두 번째와 세 번째 뷰는 android:layout_gravity="left", android:layout_gravity="right"로 설정해야 하며 높이는 match_parent로 설정되고 너비는 고정된 값인 너비입니다. 사이드 슬라이딩 메뉴.

위 설명대로 레이아웃 파일을 작성하고 Activity에 왼쪽, 오른쪽 슬라이딩을 추가하도록 설정하면 아주 간단하지 않나요~~~

예를 들어 우리 레이아웃 파일:

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

<android.support.v4.widget.DrawerLayout xmlns:android="http://schemas.android.com/apk/res/android"

  xmlns:tools="http://schemas.android.com/tools"

  android:id="@+id/id_drawerLayout"

  android:layout_width="match_parent"

  android:layout_height="match_parent"

  android:background="@drawable/img_frame_background" >

   

  <RelativeLayout

    android:layout_width="match_parent"

    android:layout_height="match_parent"

    android:background="@drawable/qq" >

   

    <Button

      android:layout_width="40dp"

      android:layout_height="30dp"

       android:layout_marginTop="10dp"

      android:layout_alignParentRight="true"

      android:background="@drawable/youce"

      android:onClick="OpenRightMenu" />

  </RelativeLayout>

   

  <fragment

    android:id="@+id/id_left_menu"

    android:name="com.zhy.demo_zhy_17_drawerlayout.MenuLeftFragment"

    android:layout_width="200dp"

    android:layout_height="match_parent"

    android:layout_gravity="left"

    android:tag="LEFT" />

   

  <fragment

    android:id="@+id/id_right_menu"

    android:name="com.zhy.demo_zhy_17_drawerlayout.MenuRightFragment"

    android:layout_width="100dp"

    android:layout_height="match_parent"

    android:layout_gravity="right"

    android:tag="RIGHT" />

   

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

로그인 후 복사

여기서 주요 콘텐츠 영역은 RelativeLayout

메뉴에 대한 두 개의 조각입니다. 왼쪽에는 200dp, 오른쪽에는 100dp가 있습니다.

알겠습니다. , 레이아웃 파일을 살펴보고 자세한 코드를 살펴보겠습니다.

3. 코드는 최고의 스승입니다

1. MenuLeftFragment의 해당 레이아웃 파일

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

package com.zhy.demo_zhy_17_drawerlayout;

   

import android.os.Bundle;

import android.support.v4.app.Fragment;

import android.view.LayoutInflater;

import android.view.View;

import android.view.ViewGroup;

   

public class MenuLeftFragment extends Fragment

{

   

  @Override

  public View onCreateView(LayoutInflater inflater, ViewGroup container,

      Bundle savedInstanceState)

  {

    return inflater.inflate(R.layout.layout_menu, container, false);

  }

}

로그인 후 복사

:

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

39

40

41

42

43

44

45

46

47

48

49

50

51

52

53

54

55

56

57

58

59

60

61

62

63

64

65

66

67

68

69

70

71

72

73

74

75

76

77

78

79

80

81

82

83

84

85

86

87

88

89

90

91

92

93

94

95

96

97

98

99

100

101

102

103

104

105

106

107

108

109

110

111

112

113

114

115

116

117

118

119

120

121

122

123

124

125

126

127

128

129

130

131

132

133

134

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

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"

  android:layout_width="match_parent"

  android:layout_height="match_parent"

  android:background="#00000000" >

   

  <LinearLayout

    android:layout_width="match_parent"

    android:layout_height="wrap_content"

    android:layout_centerVertical="true"

    android:orientation="vertical" >

   

    <RelativeLayout

      android:layout_width="match_parent"

      android:layout_height="wrap_content" >

   

      <ImageView

        android:id="@+id/one"

        android:layout_width="50dp"

        android:layout_height="50dp"

        android:layout_centerVertical="true"

        android:layout_marginLeft="20dp"

        android:layout_marginTop="20dp"

        android:src="@drawable/img_1" />

   

      <TextView

        android:layout_width="fill_parent"

        android:layout_height="wrap_content"

        android:layout_centerVertical="true"

        android:layout_marginLeft="20dp"

        android:layout_toRightOf="@id/one"

        android:text="第1个Item"

        android:textColor="#f0f0f0"

        android:textSize="20sp" />

    </RelativeLayout>

   

    <RelativeLayout

      android:layout_width="match_parent"

      android:layout_height="wrap_content" >

   

      <ImageView

        android:id="@+id/two"

        android:layout_width="50dp"

        android:layout_height="50dp"

        android:layout_centerVertical="true"

        android:layout_marginLeft="20dp"

        android:layout_marginTop="20dp"

        android:src="@drawable/img_2" />

   

      <TextView

        android:layout_width="fill_parent"

        android:layout_height="wrap_content"

        android:layout_centerVertical="true"

        android:layout_marginLeft="20dp"

        android:layout_toRightOf="@id/two"

        android:text="第2个Item"

        android:textColor="#f0f0f0"

        android:textSize="20sp" />

    </RelativeLayout>

   

    <RelativeLayout

      android:layout_width="match_parent"

      android:layout_height="wrap_content" >

   

      <ImageView

        android:id="@+id/three"

        android:layout_width="50dp"

        android:layout_height="50dp"

        android:layout_centerVertical="true"

        android:layout_marginLeft="20dp"

        android:layout_marginTop="20dp"

        android:src="@drawable/img_3" />

   

      <TextView

        android:layout_width="fill_parent"

        android:layout_height="wrap_content"

        android:layout_centerVertical="true"

        android:layout_marginLeft="20dp"

        android:layout_toRightOf="@id/three"

        android:text="第3个Item"

        android:textColor="#f0f0f0"

        android:textSize="20sp" />

    </RelativeLayout>

   

    <RelativeLayout

      android:layout_width="match_parent"

      android:layout_height="wrap_content" >

   

      <ImageView

        android:id="@+id/four"

        android:layout_width="50dp"

        android:layout_height="50dp"

        android:layout_centerVertical="true"

        android:layout_marginLeft="20dp"

        android:layout_marginTop="20dp"

        android:src="@drawable/img_4" />

   

      <TextView

        android:layout_width="fill_parent"

        android:layout_height="wrap_content"

        android:layout_centerVertical="true"

        android:layout_marginLeft="20dp"

        android:layout_toRightOf="@id/four"

        android:text="第4个Item"

        android:textColor="#f0f0f0"

        android:textSize="20sp" />

    </RelativeLayout>

   

    <RelativeLayout

      android:layout_width="match_parent"

      android:layout_height="wrap_content" >

   

      <ImageView

        android:id="@+id/five"

        android:layout_width="50dp"

        android:layout_height="50dp"

        android:layout_centerVertical="true"

        android:layout_marginLeft="20dp"

        android:layout_marginTop="20dp"

        android:src="@drawable/img_5" />

   

      <TextView

        android:layout_width="fill_parent"

        android:layout_height="wrap_content"

        android:layout_centerVertical="true"

        android:layout_marginLeft="20dp"

        android:layout_toRightOf="@id/five"

        android:text="第5个Item"

        android:textColor="#f0f0f0"

        android:textSize="20sp" />

    </RelativeLayout>

  </LinearLayout>

   

</RelativeLayout>

로그인 후 복사

사실 레이아웃 뭉치일 뿐입니다~~말할 것도 없습니다~

2.MenuRightFragment

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

package com.zhy.demo_zhy_17_drawerlayout;

   

import android.os.Bundle;

import android.support.v4.app.Fragment;

import android.view.LayoutInflater;

import android.view.View;

import android.view.ViewGroup;

   

public class MenuRightFragment extends Fragment

{

   

  @Override

  public View onCreateView(LayoutInflater inflater, ViewGroup container,

      Bundle savedInstanceState)

  {

    return inflater.inflate(R.layout.menu_layout_right, container, false);

  }

}

로그인 후 복사

해당 레이아웃 파일:

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

39

40

41

42

43

44

45

46

47

48

49

50

51

52

53

54

55

56

57

58

59

60

61

62

63

64

65

66

67

68

69

70

71

72

73

74

75

76

77

78

79

80

81

82

83

84

85

86

87

88

89

90

91

92

93

94

95

96

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

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"

  android:layout_width="match_parent"

  android:layout_height="match_parent"

  android:gravity="center_vertical"

  android:orientation="vertical" >

   

  <LinearLayout

    android:layout_width="match_parent"

    android:layout_height="wrap_content"

    android:layout_centerVertical="true"

    android:layout_gravity="center_vertical"

    android:layout_marginBottom="20dp"

    android:orientation="vertical" >

   

    <ImageView

      android:layout_width="60dp"

      android:layout_height="60dp"

      android:layout_gravity="center"

      android:src="@drawable/wode" />

   

    <TextView

      android:layout_width="fill_parent"

      android:layout_height="wrap_content"

      android:gravity="center"

      android:text="扫一扫"

      android:textColor="#ffffff" />

  </LinearLayout>

   

  <LinearLayout

    android:layout_width="match_parent"

    android:layout_height="wrap_content"

    android:layout_centerVertical="true"

    android:layout_gravity="center_vertical"

    android:layout_marginBottom="20dp"

    android:orientation="vertical" >

   

    <ImageView

      android:layout_width="60dp"

      android:layout_height="60dp"

      android:layout_gravity="center"

      android:src="@drawable/saoma" />

   

    <TextView

      android:layout_width="fill_parent"

      android:layout_height="wrap_content"

      android:gravity="center"

      android:text="讨论组"

      android:textColor="#ffffff" />

  </LinearLayout>

   

  <LinearLayout

    android:layout_width="match_parent"

    android:layout_height="wrap_content"

    android:layout_centerVertical="true"

    android:layout_gravity="center_vertical"

    android:layout_marginBottom="20dp"

    android:orientation="vertical" >

   

    <ImageView

      android:layout_width="60dp"

      android:layout_height="60dp"

      android:layout_gravity="center"

      android:src="@drawable/wode" />

   

    <TextView

      android:layout_width="fill_parent"

      android:layout_height="wrap_content"

      android:gravity="center"

      android:text="扫一扫"

      android:textColor="#ffffff" />

  </LinearLayout>

   

  <LinearLayout

    android:layout_width="match_parent"

    android:layout_height="wrap_content"

    android:layout_centerVertical="true"

    android:layout_gravity="center_vertical"

    android:layout_marginBottom="20dp"

    android:orientation="vertical" >

   

    <ImageView

      android:layout_width="60dp"

      android:layout_height="60dp"

      android:layout_gravity="center"

      android:src="@drawable/saoma" />

   

    <TextView

      android:layout_width="fill_parent"

      android:layout_height="wrap_content"

      android:gravity="center"

      android:text="讨论组"

      android:textColor="#ffffff" />

  </LinearLayout>

   

</LinearLayout>

로그인 후 복사

아직도 매우 간단합니다. 아이콘이 더 어렵다는거 다른거 찾아보세요~~

3.MainActivity
MainActivity 레이아웃 파일 올렸습니다~~

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

39

40

41

42

43

44

45

46

47

48

49

50

51

52

53

54

55

56

57

58

59

60

61

62

63

64

65

66

67

68

69

70

71

72

73

74

75

76

77

78

79

80

81

82

83

84

85

86

87

88

89

90

91

92

93

94

95

96

97

98

99

100

101

102

103

104

105

package com.zhy.demo_zhy_17_drawerlayout;

   

import android.os.Bundle;

import android.support.v4.app.FragmentActivity;

import android.support.v4.widget.DrawerLayout;

import android.support.v4.widget.DrawerLayout.DrawerListener;

import android.view.Gravity;

import android.view.View;

import android.view.Window;

   

import com.nineoldandroids.view.ViewHelper;

   

public class MainActivity extends FragmentActivity

{

   

  private DrawerLayout mDrawerLayout;

   

  @Override

  protected void onCreate(Bundle savedInstanceState)

  {

    super.onCreate(savedInstanceState);

    requestWindowFeature(Window.FEATURE_NO_TITLE);

    setContentView(R.layout.activity_main);

   

    initView();

    initEvents();

   

  }

   

  public void OpenRightMenu(View view)

  {

    mDrawerLayout.openDrawer(Gravity.RIGHT);

    mDrawerLayout.setDrawerLockMode(DrawerLayout.LOCK_MODE_UNLOCKED,

        Gravity.RIGHT);

  }

   

  private void initEvents()

  {

    mDrawerLayout.setDrawerListener(new DrawerListener()

    {

      @Override

      public void onDrawerStateChanged(int newState)

      {

      }

   

      @Override

      public void onDrawerSlide(View drawerView, float slideOffset)

      {

        View mContent = mDrawerLayout.getChildAt(0);

        View mMenu = drawerView;

        float scale = 1 - slideOffset;

        float rightScale = 0.8f + scale * 0.2f;

   

        if (drawerView.getTag().equals("LEFT"))

        {

   

          float leftScale = 1 - 0.3f * scale;

   

          ViewHelper.setScaleX(mMenu, leftScale);

          ViewHelper.setScaleY(mMenu, leftScale);

          ViewHelper.setAlpha(mMenu, 0.6f + 0.4f * (1 - scale));

          ViewHelper.setTranslationX(mContent,

              mMenu.getMeasuredWidth() * (1 - scale));

          ViewHelper.setPivotX(mContent, 0);

          ViewHelper.setPivotY(mContent,

              mContent.getMeasuredHeight() / 2);

          mContent.invalidate();

          ViewHelper.setScaleX(mContent, rightScale);

          ViewHelper.setScaleY(mContent, rightScale);

        } else

        {

          ViewHelper.setTranslationX(mContent,

              -mMenu.getMeasuredWidth() * slideOffset);

          ViewHelper.setPivotX(mContent, mContent.getMeasuredWidth());

          ViewHelper.setPivotY(mContent,

              mContent.getMeasuredHeight() / 2);

          mContent.invalidate();

          ViewHelper.setScaleX(mContent, rightScale);

          ViewHelper.setScaleY(mContent, rightScale);

        }

   

      }

   

      @Override

      public void onDrawerOpened(View drawerView)

      {

      }

   

      @Override

      public void onDrawerClosed(View drawerView)

      {

        mDrawerLayout.setDrawerLockMode(

            DrawerLayout.LOCK_MODE_LOCKED_CLOSED, Gravity.RIGHT);

      }

    });

  }

   

  private void initView()

  {

    mDrawerLayout = (DrawerLayout) findViewById(R.id.id_drawerLayout);

    mDrawerLayout.setDrawerLockMode(DrawerLayout.LOCK_MODE_LOCKED_CLOSED,

        Gravity.RIGHT);

  }

   

}

로그인 후 복사

그럼 기본적으로 댓글은 없습니다 코드 속으로~~ 비자는 어디있나요? 왜냐하면 코멘트할 내용이 별로 없기 때문입니다.

몇 가지 언급할 사항:

1. QQ의 올바른 메뉴를 시뮬레이션하려면 클릭해야 나타나므로 DrawerLayout을 초기화할 때 mDrawerLayout.setDrawerLockMode(DrawerLayout.LOCK_MODE_LOCKED_CLOSED)를 사용하세요. ,Gravity.RIGHT ); 프로그래밍만 팝업할 수 있음을 의미합니다.

마지막으로 onDrawerClosed 콜백에서 mDrawerLayout.setDrawerLockMode(DrawerLayout.LOCK_MODE_LOCKED_CLOSED,Gravity.RIGHT)를 계속 설정합니다.

2. 애니메이션은 nineoldandroids를 사용합니다. 애니메이션 정보 다양한 오프셋 및 배율 계산에 대해서는 기본적으로 동일한 Android 고모방 QQ5.0 사이드 슬라이딩 메뉴 효과 사용자 정의 컨트롤을 참조하세요. 유일한 차이점은 ViewHelper.setTranslationX(mContent, mMenu. getMeasuredWidth() * (1 - scale)); 콘텐츠가 메뉴 오른쪽에 있도록 합니다. 기본적으로 메뉴는 메뉴 위에 있으므로 그려진 거리를 기준으로 콘텐츠의 X 방향 오프셋을 설정합니다. 메뉴.

사실, 기본적으로 모든 사이드 슬라이딩 메뉴 효과를 작성할 수 있습니다. 관심이 있다면 DrawerLayout을 사용하여 이 블로그의 모든 효과를 실현할 수 있습니다. Android는 다양한 형태의 양방향 사이드 슬라이딩 메뉴를 구현합니다.

3. setDrawerListener

setDrawerListener를 사용하여 메뉴 열기 및 닫기 등을 모니터링할 수도 있습니다. 여기서 현재 동작이 어떤 메뉴인지 판단은 중력을 통해서도 판단이 가능한 것 같아요~~

자, DrawerLayout은 기본적으로 테두리에서만 메뉴를 그릴 수 있으니까요. 그러나 메뉴를 그리는 QQ의 제스처 영역은 상대적으로 넓습니다. 관심이 있는 경우 Activity의 onTouchEvent를 다시 작성하고 그 안에서 판단할 수 있습니다. 왼쪽 및 오른쪽 슬라이딩 제스처가 훌륭하다면 메뉴를 팝업하는 것이 어렵지 않습니다. ~~

QQ와 유사한 양방향 슬라이딩 메뉴를 구현하기 위해 DrawerLayout을 사용하는 Android에 대한 더 많은 기사를 보려면 PHP 중국어 웹사이트를 주목하세요!

본 웹사이트의 성명
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.
인기 튜토리얼
더>
최신 다운로드
더>
웹 효과
웹사이트 소스 코드
웹사이트 자료
프론트엔드 템플릿