많은 앱들이 카카오톡 처럼 탭 뷰페이저 형식을 사용합니다.
그래서 간단히 TabLayout + ViewPager + fragment 형식의 앱을 만들어서 공유드립니다.
다음과 같이 만들었는데요
1. 라이브러리 셋팅
compile 'com.android.support:appcompat-v7:25.2.0'
compile 'com.android.support:support-v4:25.2.0'
compile 'com.android.support:recyclerview-v7:25.2.0'
compile 'com.android.support:design:25.2.0'
- AppCompatActivity클래스는 appcompatV7 라이브러리에 포함되어 있습니다.
- ViewPager클래스는 supportV4 라이브러리에 포함되어 있습니다.
- TabLayout은 design 라이브러리에 포함되어 있습니다.
2. 소스코드
MainActivity.java
import android.support.design.widget.TabLayout;
import android.support.v4.view.ViewPager;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.Toast;
import pe.sk.com.myapplication.R;
import pe.sk.com.myapplication.adapter.MainTabPagerAdapter;
import pe.sk.com.myapplication.data.DummyContent;
import pe.sk.com.myapplication.listener.OnListFragmentInteractionListener;
public class MainActivity extends AppCompatActivity implements OnListFragmentInteractionListener {
private TabLayout mTabLayout = null; // 탭 레이아웃
private ViewPager mViewPager = null; // 뷰 페이저
private MainTabPagerAdapter mPagerAdapter = null; // 탭 어댑터
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mTabLayout = (TabLayout) findViewById(R.id.main_tab);
mViewPager = (ViewPager) findViewById(R.id.main_viewpager);
mTabLayout.setupWithViewPager(mViewPager);
mPagerAdapter = new MainTabPagerAdapter(getSupportFragmentManager(), this);
mViewPager.setAdapter(mPagerAdapter);
mViewPager.addOnPageChangeListener(new TabLayout.TabLayoutOnPageChangeListener(mTabLayout));
mTabLayout.addOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
@Override
public void onTabSelected(TabLayout.Tab tab) {
mViewPager.setCurrentItem(tab.getPosition());
}
@Override
public void onTabUnselected(TabLayout.Tab tab) {
}
@Override
public void onTabReselected(TabLayout.Tab tab) {
}
});
}
@Override
public void onListFragmentInteraction(DummyContent.DummyItem item) {
Toast.makeText(this,item.content,Toast.LENGTH_SHORT).show();
}
}
activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<android.support.v4.widget.DrawerLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:id="@+id/activity_main"
android:layout_width="match_parent"
android:layout_height="match_parent">
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="match_parent">
<android.support.design.widget.TabLayout
android:theme="@style/ThemeOverlay.AppCompat.Dark.ActionBar"
android:id="@+id/main_tab"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:background="#ff880033"
android:minHeight="?attr/actionBarSize"
app:tabIndicatorColor="#bbdefa"
app:tabSelectedTextColor="#ffffff"
app:tabTextColor="#88ffffff"
/>
<android.support.v4.view.ViewPager
android:id="@+id/main_viewpager"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_below="@id/main_tab"
/>
</RelativeLayout>
</android.support.v4.widget.DrawerLayout>
MainTabPagerAdapter.java
import android.content.Context;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentStatePagerAdapter;
import pe.sk.com.myapplication.R;
import pe.sk.com.myapplication.fragment.FirstFragment;
import pe.sk.com.myapplication.fragment.TwoFragment;
/**
* Created by P092613 on 2017-03-09.
*/
public class MainTabPagerAdapter extends FragmentStatePagerAdapter {
private final static int TAB_COUNT = 2; // 탭의 개수
private Context mContext;
private FirstFragment mFirstFragment = null;
private TwoFragment mTwoFragment = null;
private int[] mTabTitle = {R.string.first, R.string.two};
public MainTabPagerAdapter(FragmentManager fm, Context context) {
super(fm);
this.mContext = context;
}
@Override
public Fragment getItem(int position) {
switch (position) {
case 0:
mFirstFragment = FirstFragment.newInstance(1);
return mFirstFragment;
default:
mTwoFragment = TwoFragment.newInstance(1);
return mTwoFragment;
}
}
@Override
public CharSequence getPageTitle(int position) {
return mContext.getString(mTabTitle[position]);
}
@Override
public int getCount() {
return TAB_COUNT;
}
}
FirstFragment.java 와 TwoFragment.java 코드는 동일함
import android.content.Context;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import pe.sk.com.myapplication.R;
import pe.sk.com.myapplication.adapter.FirstRecyclerViewAdapter;
import pe.sk.com.myapplication.data.DummyContent;
import pe.sk.com.myapplication.listener.OnListFragmentInteractionListener;
/**
* A fragment representing a list of Items.
* <p/>
* Activities containing this fragment MUST implement the {@link OnListFragmentInteractionListener}
* interface.
*/
public class FirstFragment extends Fragment {
// TODO: Customize parameter argument names
private static final String ARG_COLUMN_COUNT = "column-count";
// TODO: Customize parameters
private int mColumnCount = 1;
private OnListFragmentInteractionListener mListener;
/**
* Mandatory empty constructor for the fragment manager to instantiate the
* fragment (e.g. upon screen orientation changes).
*/
public FirstFragment() {
}
// TODO: Customize parameter initialization
@SuppressWarnings("unused")
public static FirstFragment newInstance(int columnCount) {
FirstFragment fragment = new FirstFragment();
Bundle args = new Bundle();
args.putInt(ARG_COLUMN_COUNT, columnCount);
fragment.setArguments(args);
return fragment;
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (getArguments() != null) {
mColumnCount = getArguments().getInt(ARG_COLUMN_COUNT);
}
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_first_list, container, false);
// Set the adapter
if (view instanceof RecyclerView) {
Context context = view.getContext();
RecyclerView recyclerView = (RecyclerView) view;
if (mColumnCount <= 1) {
recyclerView.setLayoutManager(new LinearLayoutManager(context));
} else {
recyclerView.setLayoutManager(new GridLayoutManager(context, mColumnCount));
}
recyclerView.setAdapter(new FirstRecyclerViewAdapter(DummyContent.ITEMS, mListener));
}
return view;
}
@Override
public void onAttach(Context context) {
super.onAttach(context);
if (context instanceof OnListFragmentInteractionListener) {
mListener = (OnListFragmentInteractionListener) context;
} else {
throw new RuntimeException(context.toString()
+ " must implement OnListFragmentInteractionListener");
}
}
@Override
public void onDetach() {
super.onDetach();
mListener = null;
}
}
FirstRecyclerViewAdapter.java 와 TwoRecyclerViewAdapter.java 코드는 동일함
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import java.util.List;
import pe.sk.com.myapplication.R;
import pe.sk.com.myapplication.data.DummyContent.DummyItem;
import pe.sk.com.myapplication.listener.OnListFragmentInteractionListener;
/**
* {@link RecyclerView.Adapter} that can display a {@link DummyItem} and makes a call to the
* specified {@link OnListFragmentInteractionListener}.
* TODO: Replace the implementation with code for your data type.
*/
public class FirstRecyclerViewAdapter extends RecyclerView.Adapter<FirstRecyclerViewAdapter.ViewHolder> {
private final List<DummyItem> mValues;
private final OnListFragmentInteractionListener mListener;
public FirstRecyclerViewAdapter(List<DummyItem> items, OnListFragmentInteractionListener listener) {
mValues = items;
mListener = listener;
}
@Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext())
.inflate(R.layout.fragment_first, parent, false);
return new ViewHolder(view);
}
@Override
public void onBindViewHolder(final ViewHolder holder, int position) {
holder.mItem = mValues.get(position);
holder.mIdView.setText(mValues.get(position).id);
holder.mContentView.setText(mValues.get(position).content);
holder.mView.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if (null != mListener) {
// Notify the active callbacks interface (the activity, if the
// fragment is attached to one) that an item has been selected.
mListener.onListFragmentInteraction(holder.mItem);
}
}
});
}
@Override
public int getItemCount() {
return mValues.size();
}
public class ViewHolder extends RecyclerView.ViewHolder {
public final View mView;
public final TextView mIdView;
public final TextView mContentView;
public DummyItem mItem;
public ViewHolder(View view) {
super(view);
mView = view;
mIdView = (TextView) view.findViewById(R.id.id);
mContentView = (TextView) view.findViewById(R.id.content);
}
@Override
public String toString() {
return super.toString() + " '" + mContentView.getText() + "'";
}
}
}
fragment_first_list.xml
<?xml version="1.0" encoding="utf-8"?>
<android.support.v7.widget.RecyclerView
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/list"
android:name="pe.sk.com.myapplication.fragment.FirstItemFragment"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_marginLeft="16dp"
android:layout_marginRight="16dp"
app:layoutManager="LinearLayoutManager"
tools:context="pe.sk.com.myapplication.fragment.FirstFragment"
tools:listitem="@layout/fragment_first"/>
fragment_first.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="horizontal">
<TextView
android:id="@+id/id"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_margin="@dimen/text_margin"
android:textAppearance="?attr/textAppearanceListItem"/>
<TextView
android:id="@+id/content"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_margin="@dimen/text_margin"
android:textAppearance="?attr/textAppearanceListItem"/>
</LinearLayout>
끝
'Android' 카테고리의 다른 글
안드로이드 O priview 폰트 혹은 글꼴 (0) | 2017.04.25 |
---|---|
안드로이드 ProgressDialog 만들기 (0) | 2017.03.09 |
안드로이드 툴바 메뉴 보이지 않도록 설정 (0) | 2017.03.06 |
안드로이드 WheelView or StringPicker (0) | 2017.03.03 |
안드로이드 키보드 이벤트 (0) | 2017.02.23 |