Notice
Recent Posts
Recent Comments
Link
일 | 월 | 화 | 수 | 목 | 금 | 토 |
---|---|---|---|---|---|---|
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 |
Tags
- skipMemoryCache
- 행복라이브존
- divider
- Linux
- VirtualBox
- 인천SK행복드림구장
- Java
- 문학야구장
- 인천 논현동
- 게스트 확장
- diskCacheStrategy
- KIA타이거즈
- 리눅스
- 인천SK와이번스
- RecyclerView
- 인천 맛집
- 땀땀
- CentOS 7
- 조동화선수
- 버추얼박스
- 1루 응원지정석
- Android
- 이마트프랜들리존
- 조동화 은퇴식
- 안드로이드
- 정보처리기사
- SK와이번스
- 우삼겹 쌀국수
- setStyle
- textview
Archives
- Today
- Total
쭌2 블로그
[안드로이드/Android] RecyclerView 사용하기(3) - Add left and right margin to dividers 본문
IT/Android
[안드로이드/Android] RecyclerView 사용하기(3) - Add left and right margin to dividers
realjune 2018. 8. 18. 00:14이전 관련글
[안드로이드/Android] RecyclerView 사용하기(1)
RecyclerView.ItemDecoration 클래스를 상속받는 커스텀 클래스를 작성하여 사용하면
RecyclerView의 Divider를 쉽게 조작할 수 있습니다.
이번에는 SimpleDividerItemDecoration 클래스를 작성하여 Divider의 왼쪽, 오른쪽 margin을 추가해보겠습니다.
1. SimpleDividerItemDecoration.java
RecyclerView.ItemDecoration 클래스를 상속받는 커스텀 클래스를 작성합니다.
public class SimpleDividerItemDecoration extends RecyclerView.ItemDecoration {
private Drawable mDivider;
private Resources resources;
public SimpleDividerItemDecoration(Resources resources) {
this.resources = resources;
mDivider = this.resources.getDrawable(R.drawable.divider);
}
public void onDrawOver(Canvas c, RecyclerView parent, RecyclerView.State state) {
int left = this.resources.getDimensionPixelSize(R.dimen.margin_20);
int right = parent.getWidth() - this.resources.getDimensionPixelSize(R.dimen.margin_20);
int childCount = parent.getChildCount();
for (int i = 0; i < childCount; i++) {
View child = parent.getChildAt(i);
RecyclerView.LayoutParams params = (RecyclerView.LayoutParams) child.getLayoutParams();
int top = child.getBottom() + params.bottomMargin;
int bottom = top + mDivider.getIntrinsicHeight();
mDivider.setBounds(left, top, right, bottom);
mDivider.draw(c);
}
}
}
소스를 잠깐 살펴볼까요?
mDivider = this.resources.getDrawable(R.drawable.divider);
Drawable 변수에 미리 정의해놓은 divider.xml 파일을 초기화 해줍니다.
int left = this.resources.getDimensionPixelSize(R.dimen.margin_20);
int right = parent.getWidth() - this.resources.getDimensionPixelSize(R.dimen.margin_20);
onDrawOver() 함수 안에서 Divider에 추가할 왼쪽, 오른쪽 마진을 설정해줍니다.
recyclerView.addItemDecoration(new SimpleDividerItemDecoration(getResources()));
그리고 이제 RecyclerView의 addItemDecoration() 함수로 작성한 커스텀 클래스를 추가해주면 끝.
2. 결과
아래 결과 화면입니다.
모든 Divider에 왼쪽, 오른쪽 마진이 추가된 것이 보이시죠?
'IT > Android' 카테고리의 다른 글
[안드로이드/Android] Java 코드에서 TextView setStyle 적용하기 (0) | 2018.09.06 |
---|---|
[안드로이드/Android] dp 단위를 px 단위로 변환하는 2가지 방법 (0) | 2018.08.22 |
[안드로이드/Android] getDimension(), getDimensionPixelSize() 함수 차이점 (0) | 2018.08.13 |
[안드로이드/Android] RecyclerView 사용하기(2) - Add dividers to RecyclerView (0) | 2018.08.06 |
[안드로이드/Android] setOnTabSelectedListener is depreated (0) | 2018.08.06 |
Comments