Android RecyclerView UI 의 스크롤 컨트롤 예시
RecyclerView 는 증강 판 ListView 라 고 할 수 있다.이 는 ListView 와 같은 효 과 를 실 현 했 을 뿐만 아니 라 ListView 에 존재 하 는 여러 가지 부족 도 최적화 시 켰 다.RecyclerView 는 현재 공식 적 으로 추천 하 는 스크롤 컨트롤 입 니 다.O(∩∩)O~
기본 용법
RecyclerView 도 새로 추 가 된 컨트롤 이 므 로 프로젝트 의 build.gradle 에 해당 하 는 의존 라 이브 러 리 를 추가 해 야 사용 할 수 있 습 니 다.
compile 'com.android.support:recyclerview-v7:24.2.1'
철자 가 틀 리 지 않도록 주의 하 세 요.O(∩∩)O~추가 후 Sync Now 링크 를 클릭 하 세 요.
다음 레이아웃 파일 수정:
<?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.support.v7.widget.RecyclerView
android:id="@+id/recycler_view"
android:layout_width="match_parent"
android:layout_height="match_parent" />
</LinearLayout>
여기 서 너비 와 높이 를 match 로 정의 합 니 다.parent,이렇게 하면 RecyclerView 가 전체 화면 을 차지 할 수 있 습 니 다.RecyclerView 도 시스템 에 내 장 된 SDK 가 아니 기 때문에 완전한 패키지 경 로 를 참조 합 니 다.그리고 RecyclerView 에 어댑터 를 만 듭 니 다(RecyclerView 에서 계승 합 니 다.Adapter
public class CatAdapter extends RecyclerView.Adapter<CatAdapter.ViewHolder> {
private List<Cat> cats;
static class ViewHolder extends RecyclerView.ViewHolder {
ImageView image;
TextView name;
public ViewHolder(View view) {
super(view);
image = (ImageView) view.findViewById(R.id.image);
name = (TextView) view.findViewById(R.id.name);
}
}
public CatAdapter(List<Cat> cats) {
this.cats = cats;
}
@Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.cat_item, parent, false);
return new ViewHolder(view);
}
@Override
public void onBindViewHolder(ViewHolder holder, int position) {
Cat cat = cats.get(position);
holder.image.setImageResource(cat.getImageId());
holder.name.setText(cat.getName());
}
@Override
public int getItemCount() {
return cats.size();
}
}
코드 에서,우 리 는 먼저 내부 클래스 인 ViewHolder 를 정 의 했 습 니 다.이것 은 RecyclerView.ViewHolder 에서 계승 합 니 다.그 다음 에 View Holder 의 구조 함수 에 View 인 자 를 전달 합 니 다.이것 은 RecyclerView 하위 항목 의 가장 바깥쪽 구조 이기 때문에 우 리 는 이 를 통 해 레이아웃 중의 ImageView 와 TextView 의 인 스 턴 스 를 얻 을 수 있 습 니 다.CatAdapter 의 구조 함 수 는 보 여줄 데이터 원본 을 전달 하고 클래스 변수 cats 에 값 을 부여 하 는 데 사 용 됩 니 다.
CatAdapter 는 RecyclerView.Adapter 에서 계승 하기 때문에 다음 세 가지 방법 을 다시 써 야 합 니 다.
public class MainActivity extends AppCompatActivity {
private List<Cat> cats = new ArrayList<>();
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
init();
RecyclerView recyclerView=(RecyclerView)findViewById(R.id.recycler_view);
LinearLayoutManager layoutManager=new LinearLayoutManager(this);
recyclerView.setLayoutManager(layoutManager);
CatAdapter adapter=new CatAdapter(cats);
recyclerView.setAdapter(adapter);
}
/**
*
*/
private void init() {
cats.add(new Cat(" ", R.drawable.cat1));
cats.add(new Cat(" ", R.drawable.cat2));
cats.add(new Cat(" ", R.drawable.cat3));
cats.add(new Cat(" ", R.drawable.cat4));
cats.add(new Cat(" ", R.drawable.cat5));
cats.add(new Cat(" ", R.drawable.cat6));
cats.add(new Cat(" ", R.drawable.cat7));
cats.add(new Cat(" ", R.drawable.cat8));
cats.add(new Cat(" ", R.drawable.cat9));
cats.add(new Cat(" ", R.drawable.cat10));
cats.add(new Cat(" ", R.drawable.cat11));
cats.add(new Cat(" ", R.drawable.cat12));
}
}
LinearLayoutManager 의 선형 레이아웃 대상 을 만 들 고 recyclerView.setLayoutManager()방법 에 전달 합 니 다.recyclerView 예시
우 리 는 recyclerView 를 사용 하여 ListView 의 효 과 를 만 들 었 고 코드 논리 가 더욱 뚜렷 해 졌 다.
2 가로 스크롤
이제 이 고양이 들 을 가로 스크롤 로 바 꿉 시다.
catitem 의 요 소 를 수직 으로 배열 합 니 다:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="110dp"
android:layout_height="wrap_content"
android:orientation="vertical"
>
<ImageView
android:id="@+id/image"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center_horizontal"
/>
<TextView
android:id="@+id/name"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center_horizontal"
android:layout_marginTop="10dp" />
</LinearLayout>
여기에 LinearLayout 의 너 비 를 110 dp,즉 고정된 값 으로 설정 합 니 다.고양이 마다 문자 길이 가 다 르 기 때문에 wrap 을 사용 하면content 는 하위 항목 의 길이 가 일치 하지 않 을 수 있 습 니 다.match 로parent 는 또 하나의 키 항목 이 전체 화면 을 차지 하 게 될 것 이다.우 리 는 ImageView 와 TextView 를 모두 수평 으로 가운데 로 설정 하고 android:layot 를 사용 합 니 다.margin Top,텍스트 와 그림 을 거 리 를 두 면 더욱 아름 답 습 니 다.
다음은 이벤트 클래스 의 코드 를 수정 합 니 다.
@Override
protected void onCreate(Bundle savedInstanceState) {
...
layoutManager.setOrientation(LinearLayoutManager.HORIZONTAL);
...
}
LinearLayoutManager 의 레이아웃 을 가로 배열 로 바 꿉 니 다(기본 값 은 세로 배열).가로 배열
우 리 는 화면 밖의 고양 이 를 수평 방향 으로 미끄러져 볼 수 있다.
ListView 의 레이아웃 배열 은 자신 이 관리 하기 때문에 한계 가 있 습 니 다.그리고 RecyclerView 는 레이아웃 작업 을 LayoutManager 에 맡 겼 습 니 다.LayoutManager 는 일련의 확장 가능 한 레이아웃 배열 인 터 페 이 스 를 제 정 했 습 니 다.그래서 우 리 는 인터페이스의 규범 에 따라 실현 하면 다양한 배열 방식 의 레이아웃 을 맞 출 수 있 습 니 다.O(∩∩)O~
3 폭포 흐름 배치
Staggered GridLayoutManager 를 사용 하여 멋 진 폭포 흐름 구 조 를 실현 합 시다 O(∩∩)O~
우선 cat 수정아 이 템 레이아웃 파일:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical"
android:layout_margin="5dp"
>
<ImageView
android:id="@+id/image"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center_horizontal"
/>
<TextView
android:id="@+id/name"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="left"
android:layout_marginTop="10dp" />
</LinearLayout>
여 기 는 LinearLayout 의 너 비 를 wrap 로 바 꿉 니 다.content,이러한 폭 은 실제 레이아웃 열 수 에 따라 자동 으로 적 용 됩 니 다.layot 도 사용margin 은 하위 항목 사이 에 일정한 간격 을 남 깁 니 다.마지막 으로 TextView 를 왼쪽 정렬 으로 변경 합 니 다.아래 설명 파일 의 내용 이 길 수 있 기 때 문 입 니 다.O(∩∩)O~활성 클래스 의 코드 수정:
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
init();
RecyclerView recyclerView = (RecyclerView) findViewById(R.id.recycler_view);
StaggeredGridLayoutManager layoutManager=new StaggeredGridLayoutManager(3,StaggeredGridLayoutManager.VERTICAL);
recyclerView.setLayoutManager(layoutManager);
CatAdapter adapter = new CatAdapter(cats);
recyclerView.setAdapter(adapter);
}
여기 서 저 희 는 Staggered GridLayoutManager 의 인 스 턴 스 를 만 들 었 습 니 다.구조 함 수 는 두 개의 인 자 를 받 아들 이 고 첫 번 째 인 자 는 레이아웃 의 열 수 를 지정 하 는 데 사용 되 며 두 번 째 인 자 는 레이아웃 의 배열 방향 을 지정 하 는 데 사 용 됩 니 다.폭포 흐름 예시
4 클릭 이벤트
RecyclerView 는 ListView 와 같은 setOnItemClickListener()이벤트 가 없 기 때문에 하위 항목 의 구체 적 인 View 에 클릭 이 벤트 를 등록 해 야 합 니 다.
ListView 의 setOnItemClickListener()는 하위 항목 의 클릭 이벤트 로 등록 되 어 있 지만,하위 항목 의 구체 적 인 단 추 를 누 르 려 면 ListView 를 사용 하 는 것 이 번 거 롭 습 니 다.그래서 RecyclerView 는 하위 항목 클릭 이벤트 의 모니터 를 직접 제거 하고 모든 클릭 이 벤트 를 구체 적 인 View 에 맡 겨 등록 합 니 다.O(∩∩)O
어댑터 수정:
static class ViewHolder extends RecyclerView.ViewHolder {
View catView;
ImageView image;
TextView name;
public ViewHolder(View view) {
super(view);
catView = view;
image = (ImageView) view.findViewById(R.id.image);
name = (TextView) view.findViewById(R.id.name);
Log.d(TAG, "ViewHolder: image:" + image);
Log.d(TAG, "ViewHolder: name:" + name);
}
}
public CatAdapter(List<Cat> cats) {
this.cats = cats;
}
@Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.cat_item, parent, false);
final ViewHolder holder = new ViewHolder(view);
holder.catView.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
int position = holder.getAdapterPosition();
Cat cat = cats.get(position);
Toast.makeText(v.getContext(), " View " + cat.getName(), Toast.LENGTH_SHORT).show();
}
});
holder.image.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
int position = holder.getAdapterPosition();
Log.d(TAG, "onClick: position:" + position);
Cat cat = cats.get(position);
Toast.makeText(v.getContext(), " " + cat.getName(), Toast.LENGTH_SHORT).show();
}
});
return holder;
}
우 리 는 가장 바깥쪽 의 레이아웃 과 ImageView 를 위해 클릭 이 벤트 를 등 록 했 는데 이것 이 바로 RecyclerView 의 유연성 이다.RecyclerView 클릭 이벤트 실행
그림 아래 글 자 를 클릭 하면 ImageView 의 클릭 이벤트 가 발생 합 니 다.이벤트 가 외부 로 전송 되 기 때 문 입 니 다.O(∩∩)O~
이상 이 바로 본 고의 모든 내용 입 니 다.여러분 의 학습 에 도움 이 되 고 저 희 를 많이 응원 해 주 셨 으 면 좋 겠 습 니 다.
이 내용에 흥미가 있습니까?
현재 기사가 여러분의 문제를 해결하지 못하는 경우 AI 엔진은 머신러닝 분석(스마트 모델이 방금 만들어져 부정확한 경우가 있을 수 있음)을 통해 가장 유사한 기사를 추천합니다:
Bitrise에서 배포 어플리케이션 설정 테스트하기이 글은 Bitrise 광고 달력의 23일째 글입니다. 자체 또는 당사 등에서 Bitrise 구축 서비스를 사용합니다. 그나저나 며칠 전 Bitrise User Group Meetup #3에서 아래 슬라이드를 발표했...
텍스트를 자유롭게 공유하거나 복사할 수 있습니다.하지만 이 문서의 URL은 참조 URL로 남겨 두십시오.
CC BY-SA 2.5, CC BY-SA 3.0 및 CC BY-SA 4.0에 따라 라이센스가 부여됩니다.