woong's

Android CoordinatorLayout Behavior 사용하기 본문

Develop/Android

Android CoordinatorLayout Behavior 사용하기

dlsdnd345 2016. 3. 30. 16:43
336x280(권장), 300x250(권장), 250x250, 200x200 크기의 광고 코드만 넣을 수 있습니다.

Android CoordinatorLayout Behavior 사용하기


android support design 라이브러리가 생기면서 behavior 라는 개념이 생겼습니다.

여태까지는 android 에서 정의한 behavior 를 사용 했습니다. 사용하면서 어떻게 만들었는지

의문이 있었지만 , 찾아보지 않아 이번에 기회가 있어 이렇게 찾아서 정리해보려 합니다.


behavior 는 view 에 의존하여 어떤뷰의 행동에 따라 위젯을 변경하는 것입니다.


이 포스트를 통해서는 간단한 behavior 를 작성하려합니다.

간단하지만 방법만 알면 얼마든지 응용이 가능한것 같습니다.


사전준비 작업


우선 간단하게 CoordinatorLayout 에 FloationgButton 선택시 snackBar 가 나타나는 화면을

구성해 보겠습니다. 위 위젯을 사용하기 위해서 design 라이브러리를 추가 합니다.


1
2
3
4
5
6
7
8
 
dependencies {
    compile fileTree(include: ['*.jar'], dir: 'libs')
    testCompile 'junit:junit:4.12'
    compile 'com.android.support:appcompat-v7:23.2.1'
    compile 'com.android.support:design:24.0.0-alpha1'
}
 
cs


design 라이브러리를 추가 합니다.


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
 
<?xml version="1.0" encoding="utf-8"?>
<android.support.design.widget.CoordinatorLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="match_parent">
 
    <android.support.design.widget.FloatingActionButton
        android:id="@+id/fab"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="end|bottom"
        android:layout_margin="16dp"
         />
 
</android.support.design.widget.CoordinatorLayout>
 
cs


화면은 CoordinatorLayout 에 FloationgButton 을 만들었습니다.


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
 
public class MainActivity extends AppCompatActivity {
 
    FloatingActionButton fab;
 
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
 
 
        fab = (FloatingActionButton) findViewById(R.id.fab);
        fab.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Snackbar.make(v, "Hello World", Snackbar.LENGTH_LONG).show();
            }
        });
 
    }
 
}
 
cs


FloationgButton 선택시 snackBar가 나타나도록 했습니다. 이렇게 구성하고 버튼을 선택해보면 snackBar가

나타나면서 FloationgButton 을 밀어 올리고 사라지면서 제자리로 오는것을 볼수 있습니다.

위와 같이 동작을 만들기 위해서 필요한것이 behavior 입니다.


위와 같이 동작하는 Custom Behavior 를 만들어 보려 합니다.


Behavior 코드 작성


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
 
public class FloatingActionButtonBehavior extends CoordinatorLayout.Behavior<FloatingActionButton> {
 
    private static final String TAG = "FloatingActionButtonBehavior";
 
    public FloatingActionButtonBehavior() {
    }
 
    public FloatingActionButtonBehavior(Context context, AttributeSet attrs) {
        super(context, attrs);
    }
 
 
}
 
cs


위와 같이 빈 Behavior 를 작성 하였습니다. 위와 같이 작성후에 behavior 를 적용해 보겠습니다.


1
2
3
4
5
6
7
8
9
10
 
<android.support.design.widget.FloatingActionButton
    android:id="@+id/fab"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_gravity="end|bottom"
    android:layout_margin="16dp"
    app:layout_behavior="com.android.woong.behaviorsample.FloatingActionButtonBehavior"
     />
 
cs


위와 같이 적용하고 실행해서 FloationgButton 선택해보면 snackBar 가 나타나지만 FloationgButton 이 가만히 있는것을 알 수 있습니다.

행동이 없기 때문입니다.


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
 
public class FloatingActionButtonBehavior extends CoordinatorLayout.Behavior<FloatingActionButton> {
 
    private static final String TAG = "FloatingActionButtonBehavior";
 
    public FloatingActionButtonBehavior() {
    }
 
    public FloatingActionButtonBehavior(Context context, AttributeSet attrs) {
        super(context, attrs);
    }
 
 
    @Override
    public boolean layoutDependsOn(CoordinatorLayout parent, FloatingActionButton child, View dependency) {
        return dependency instanceof Snackbar.SnackbarLayout;
    }
 
    @Override
    public boolean onDependentViewChanged(CoordinatorLayout parent, FloatingActionButton child, View dependency) {
 
        float translationY = Math.min(0,dependency.getTranslationY() - dependency.getHeight());
        child.setTranslationY(translationY);
 
        return true;
    }
 
}
 
cs


Behavior 를 작성해 보았습니다. 상속을 통해서 어떤뷰에서 Behaivor 를 사용할지 정의를 합니다.

layoutDependsOn 함수로 이벤트가 들어 옵니다. 이함수는 의존할 View를 Filter 하는 역할을 하는것 같습니다.

위와 같이 dependency 의 타입이 snackbarLayout 일때 리턴을 통해서 onDependentViewChanged 함수로

이벤트가 전달 됩니다. 


onDependentViewChanged 함수는 dependency 의 View의  변화가 있을때 이벤트가 들어 옵니다. 



위 코드를 작성하면 snackBar 의 변화가 있을때 이벤트가 호출됩니다. 나타나면서 움직일때 , 사라지면서 움직일때의 이벤트가 호출됩니다.

snackBar의 이동 Y 값을 FloationgButton 에 적용 시켜주기 때문에 아까와 같은 동작의 Behavior를 만들수 있습니다.

이와 같이 행동을 만들고 응용을하면 구글플레이 메인화면 , 이쁜 화면들을 만들수 있을것 같습니다.






'Develop > Android' 카테고리의 다른 글

홈 버튼 오버라이드  (0) 2016.07.14
Android Zxing 사용하기  (1) 2016.05.10
Android Templates 사용하기  (0) 2016.03.30
Android BottomSheetsBehavior 사용하기  (0) 2016.03.15
Android DB Realm 사용하기  (2) 2016.03.14
Comments