안녕세계
[안드로이드] RecyclerView With TabLayout (Feat. ViewPager) 본문
[안드로이드] RecyclerView With TabLayout (Feat. ViewPager)
Junhong Kim 2017. 1. 12. 20:12& 필요한 파일 &
[ JAVA Class ]
* Activity
MainActivity.java
ㄴ ViewPager의 코드가 위치할 곳
*Adapter
BucketAdapter.java
ㄴ RecyclerView의 Adapter
TabPagerAdapter.java
ㄴ ViewPager의 Adapter
*Fragment
processingFragment.java
ㄴFragment의 내용
completedFragment.java
ㄴFragment의 내용
*Item
BucketItem.java
ㄴRecyclerView의 Row Item
[ RESOURCE File ]
activitiy_main.xml
fragment_processing.xml (= Fragment 1)
fragment_completed.xml (= Fragment 2)
item_bucket (= RecyclerView의 Row가 될 Layout)
[Step 1]
dependencies {
compile 'com.android.support:design:25.0.0'
}
android support library를 사용하기 위해서 위 라이브러리를 gradle 에 추가하고 sync를 맞춰 줍니다.
[Step 2]
activitiy_main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/activity_main"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context="com.jnj.kickthebucket.Activity.MainActivity">
<android.support.design.widget.TabLayout
android:id="@+id/tabLayout"
android:layout_width="match_parent"
android:layout_height="wrap_content"
app:tabIndicatorColor="@color/colorPrimary" />
<android.support.v4.view.ViewPager
android:id="@+id/viewPager"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#ffffff" />
</LinearLayout>
MainActivitiy에는 TabLayout과 ViewPager를 넣습니다.
[Step 3]
fragment_processing.xml
<?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:orientation="vertical">
<android.support.v7.widget.RecyclerView
android:layout_margin="5dp"
android:id="@+id/processing_list"
android:layout_width="match_parent"
android:layout_height="match_parent" />
</LinearLayout>
fragment_completed.xml
<?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:orientation="vertical">
<android.support.v7.widget.RecyclerView
android:layout_margin="5dp"
android:id="@+id/processing_list"
android:layout_width="match_parent"
android:layout_height="match_parent" />
</LinearLayout>
TabLayout을 활용하여 2개의 Fragment를 이동할 것 이므로 Fragment에는 아무거나 넣어도 됩니당
[Step 3]
Item_bucket.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/bucket_item_layout"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical">
<TextView
android:id="@+id/bucket_title"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Bucket Title"
android:textColor="#000000"
android:textSize="20dp" />
<TextView
android:id="@+id/bucket_date"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Date"
android:textSize="10dp" />
<View
android:layout_width="match_parent"
android:layout_height="1dp"
android:background="#eaeaea" />
</LinearLayout>
RecyclerView의 Row 아이템이 될 Layout을 만들어 줍니다.
[Step 4]
Item_bucket.java
public class BucketItem {
String title;
String date;
public BucketItem(String title, String date) {
this.title = title;
this.date = date;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getDate() {
return date;
}
public void setDate(String date) {
this.date = date;
}
}
ButketItem의 Value Object 클래스를 만들어주고 Setter/getter를 만들어줍니다.
[Step 5]
public class CompletedFragment extends Fragment {
RecyclerView completedList;
BucketAdapter adapter;
Paint p = new Paint();
@Nullable
@Override
public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_completed, container, false);
completedList = (RecyclerView) view.findViewById(R.id.completed_list);
LinearLayoutManager lm = new LinearLayoutManager(getActivity(), LinearLayoutManager.VERTICAL, false);
completedList.setLayoutManager(lm);
List<BucketItem> bucketItems = new ArrayList<>();
BucketItem[] bucketItem = new BucketItem[5];
for(int i = 0; i < 5; i++) {
bucketItem[i] = new BucketItem("완료", "2017-01-31");
bucketItems.add(bucketItem[i]);
}
completedList.setAdapter(new BucketListAdapter(getActivity(), bucketItems, R.layout.fragment_processing));
return view;
Fragment에서 layout을 사용하기 위해서 inflate하여 해당 아이템과 리니어 매니저를 통해서 지정하고
아답터를 여결
[Step 6]
public class BucketAdapter extends RecyclerView.Adapter<BucketAdapter.ViewHolder> {
Context context;
List<BucketItem> items;
public BucketAdapter(Context context, List<BucketItem> items) {
this.context = context;
this.items = items;
}
@Override
public BucketAdapter.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View v = LayoutInflater.from(parent.getContext()).inflate(R.layout.item_bucket, null);
return new ViewHolder(v);
}
@Override
public void onBindViewHolder(BucketAdapter.ViewHolder holder, int position) {
BucketItem item = items.get(position);
holder.bucketItemLayout.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Toast.makeText(context, "테스트", Toast.LENGTH_SHORT).show();
Intent intent = new Intent(context, DetailActivity.class);
context.startActivity(intent);
}
});
holder.bucketTitle.setText(item.getTitle());
holder.bucketDate.setText(item.getDate());
}
@Override
public int getItemCount() {
return this.items.size();
}
public class ViewHolder extends RecyclerView.ViewHolder {
LinearLayout bucketItemLayout;
TextView bucketTitle;
TextView bucketDate;
public ViewHolder(View itemView) {
super(itemView);
bucketItemLayout = (LinearLayout) itemView.findViewById(R.id.bucket_item_layout);
bucketTitle = (TextView) itemView.findViewById(R.id.bucket_title);
bucketDate = (TextView) itemView.findViewById(R.id.bucket_date);
}
}
}
[Step 7]
public class TabPagerAdapter extends FragmentPagerAdapter {
List<Fragment> listFragments;
public TabPagerAdapter(FragmentManager fm, List<Fragment> listFragments) {
super(fm);
this.listFragments = listFragments;
}
@Override
public Fragment getItem(int position) {
return listFragments.get(position);
}
@Override
public int getCount() {
return listFragments.size();
}
}
프래그먼트들을 하나의 아댑터에서 관리 해주기 위한 작업
[Step 8]
public class MainActivity extends AppCompatActivity {
TabLayout tabLayout;
ViewPager viewPager;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
initViewPager();
}
private void initViewPager() {
viewPager = (ViewPager) findViewById(R.id.viewPager);
// 프래그먼트 리스트에 추가
List<Fragment> listFragments = new ArrayList<>();
listFragments.add(new ProcessingFragment());
listFragments.add(new CompletedFragment());
// 탭 어댑터에 리스트 넘겨준 후 뷰페이저 연결
TabPagerAdapter fragmentPagerAdapter = new TabPagerAdapter(getSupportFragmentManager(), listFragments);
viewPager.setAdapter(fragmentPagerAdapter);
// 각 탭 이름 지정
tabLayout = (TabLayout) findViewById(R.id.tabLayout);
tabLayout.addTab(tabLayout.newTab().setText("프래그먼트A"));
tabLayout.addTab(tabLayout.newTab().setText("프래그먼트B"));
tabLayout.setTabTextColors(Color.LTGRAY, Color.BLUE);
/* 뷰페이저 이동했을때 & 탭 눌렀을때 해당 위치로 이동 */
viewPager.addOnPageChangeListener(new TabLayout.TabLayoutOnPageChangeListener(tabLayout));
tabLayout.setOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
@Override
public void onTabSelected(TabLayout.Tab tab) {
switch (tab.getPosition()) {
case 0:
viewPager.setCurrentItem(tab.getPosition());
break;
case 1:
viewPager.setCurrentItem(tab.getPosition());
break;
}
}
@Override
public void onTabUnselected(TabLayout.Tab tab) {
}
@Override
public void onTabReselected(TabLayout.Tab tab) {
}
});
}
}
NEXT POST =>
RecyclerView 좌/우 Swipe 구현 (feat. ItemTouchHelper)
[참고]
https://www.learn2crack.com/2016/02/custom-swipe-recyclerview.html
'Client > Android' 카테고리의 다른 글
[안드로이드] Toolbar (0) | 2017.01.17 |
---|---|
[안드로이드] RecyclerView - Divider 생성 (0) | 2017.01.16 |
[라이브러리] Buttef Knife 8.4.0 (0) | 2016.11.25 |
[안드로이드] SimpleDateFormat (날짜형식 변경) (0) | 2016.11.01 |
[라이브러리] Retrofit 1.9 사용법 (Android ↔ Node.js 통신) (0) | 2016.10.31 |