티스토리 뷰
안녕하세요.
휴가와 업무가 겹처 5일만에 글을 작성하네요.
처음 시작할 때 마음 가짐으로
다시 열정적으로 작성해 보겠습니다.
오늘은 탭 스와이프에 대해 학습하겠습니다.
기존에 제작했던 앱에 탭 스와이프 기능을
넣으라는 요청사항이 있었습니다.
예전에 스와이프 기능을 혼자 만들어 보려
애니메이션 넣고 했던 기억이 있는데
그렇게 만들다 보니
스와이프가 엄청 부자연스럽더라구요.
그래서 안드로이드에서 제공하는 스와이프를
소스에 적용해 보려 합니다.
역시 구글링을 시작해 보도록 하겠습니다.
구글링 결과 위 기능은 안드로이드 3.0 부터
사용이 가능하다 합니다.
요즘 안드로이드3.0 쓰시는 분들이 거의 없을
것으로 판단됩니다(현재 7까지 나왔어요)
그럼 조건에 만족하기 때문에 바로 시작해
보도록 하겠습니다.
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
}
우선 테스트를 위해 프로젝트
하나를 생성했습니다.
아래는 안드로이드 gradle 환경입니다.
apply plugin: 'com.android.application'
android {
compileSdkVersion 26
buildToolsVersion "26.0.1"
defaultConfig {
applicationId "com.example.parkhyeonje.ttttttttttt"
minSdkVersion 15
targetSdkVersion 26
versionCode 1
versionName "1.0"
testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
}
buildTypes {
release {
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
}
}
}
dependencies {
compile fileTree(dir: 'libs', include: ['*.jar'])
androidTestCompile('com.android.support.test.espresso:espresso-core:2.2.2', {
exclude group: 'com.android.support', module: 'support-annotations'
})
compile 'com.android.support:appcompat-v7:26.+'
compile 'com.android.support.constraint:constraint-layout:1.0.2'
testCompile 'junit:junit:4.12'
}
다시 MainActivity 로 돌아가서 본격적으로
스와이프 기능을 구현해 보도록 하겠습니다.
우선 전체적인 틀을 설명하자면
메인, 서브1, 서브2 플래그먼트를 통해
스와이프가 동작할 수 있게끔 하겠습니다.
가장먼저 MainActivity 클래스 안에
FragmentPagerAdapter 가 상속된
클래스를 하나 만들도록 하겠습니다.
FragmentPagerAdapter 를 한개의 생성자와
상속받으면 2개의 메소드가
오버라이드 되어 자동으로 생성됩니다.
public class SectionsPagerAdapter extends FragmentPagerAdapter {
public SectionsPagerAdapter(FragmentManager fm) {
super(fm);
}
@Override
public Fragment getItem(int position) {
return null;
}
@Override
public int getCount() {
return 0;
}
}
메소드를 간략하게 설명하자면
getItem 메소드는 이동할 서브클래스드를
정의하는 곳이고
getCount는 총 스와이프될
페이지수를 적어두시면 됩니다.
저 같은경우 테스트용으로 2개의 페이지를
제작할 것이므로
아래와 같이 수정해 주었습니다.
@Override
public Fragment getItem(int position) {
switch (position) {
case 0:
return new 이동할 첫번째 페이지(mContext);
case 1:
return new 이동할 두번째 페이지(mContext);
}
return null;
}
@Override
public int getCount() {
// Show 2 total pages.
return 2;
}
그리고 getCount 메소드 아래에
탭의 Title 을 정의할 메소드를 오버라이드
해 보겠습니다.
@Override
public CharSequence getPageTitle(int position) {
return null;
}
그리고 position 값에 따라 타이틀 이름이
변경될 수 있도록
아래와 같이 소스를 추가해 줍니다.
@Override
public CharSequence getPageTitle(int position) {
Locale l = Locale.getDefault();
switch (position) {
case 0:
return getString(R.string.title_section1).toUpperCase(l);
case 1:
return getString(R.string.title_section2).toUpperCase(l);
}
return null;
}
SectionsPagerAdapter 를
MainActivity 에 상속하여 줍니다.
public class MainActivity extends FragmentActivity {
SectionsPagerAdapter mSectionsPagerAdapter;
그리고 SectionsPagerAdapter 의 생성자에
맞게 매개변수를 전달하여 줍니다.
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mSectionsPagerAdapter = new SectionsPagerAdapter(
getApplicationContext(), getSupportFragmentManager());
이상으로 페이지를 연결해줄 어댑터
작업은 끝이 났습니다.
그럼 이제 뷰페이저를 통해
실질적으로 페이지들을 연결할 수 있도록
작업해 보도록 하겠습니다.
public class MainActivity extends FragmentActivity {
SectionsPagerAdapter mSectionsPagerAdapter;
ViewPager mViewPager;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mSectionsPagerAdapter = new SectionsPagerAdapter(
getApplicationContext(), getSupportFragmentManager());
// Set up the ViewPager with the sections adapter.
mViewPager = (ViewPager) findViewById(R.id.pager);
mViewPager.setAdapter(mSectionsPagerAdapter);
}
그리고 activity_main xml 에
<android.support.v4.view.ViewPager xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/pager"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity" >
<!--
This title strip will display the currently visible page title, as well as the page
titles for adjacent pages.
-->
<android.support.v4.view.PagerTitleStrip
android:id="@+id/pager_title_strip"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_gravity="top"
android:background="#33b5e5"
android:paddingBottom="4dp"
android:paddingTop="4dp"
android:textColor="#fff" />
</android.support.v4.view.ViewPager>
다음과 같이 작성해 줍니다.
PagerTitleStrip 은 탭타이틀이
들어갈 부분이고
ViewPager 은 스와이프
기능이 들어갈 전체적인 페이지를
의미합니다.
아래는 MainActivity 전체적인 소스입니다.
public class MainActivity extends FragmentActivity {
SectionsPagerAdapter mSectionsPagerAdapter;
ViewPager mViewPager;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mSectionsPagerAdapter = new SectionsPagerAdapter(
getApplicationContext(), getSupportFragmentManager());
mViewPager = (ViewPager) findViewById(R.id.pager);
mViewPager.setAdapter(mSectionsPagerAdapter);
}
public class SectionsPagerAdapter extends FragmentPagerAdapter {
Context mContext;
public SectionsPagerAdapter(Context mContext, FragmentManager fm) {
super(fm);
this.mContext = mContext;
}
@Override
public Fragment getItem(int position) {
switch (position) {
case 0:
return new Tab1(mContext);
case 1:
return new Tab2(mContext);
}
return null;
}
@Override
public int getCount() {
return 2;
}
@Override
public CharSequence getPageTitle(int position) {
Locale l = Locale.getDefault();
switch (position) {
case 0:
return getString(R.string.title_section1).toUpperCase(l);
case 1:
return getString(R.string.title_section2).toUpperCase(l);
}
return null;
}
}
}
이제 서브페이지를 제작해 보도록 하겠습니다.
저는 서브페이지 이름을 Tab1, Tab2로
하였고 Fragment 를 상속하도록 하였습니다.
Tab1 클래스는 일반 엑티비티와달리
onCreateView 를 오버라이드 하여 사용하여야
합니다.
다음은 서브 페이지 전체소스 입니다.
public class Tab1 extends Fragment {
Context mContext;
public Tab1(Context context) {
mContext = context;
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.activity_tabs1, null);
return view;
}
}
이상으로 스와이프에 대한
테스트를 해보았습니다.
'안드로이드' 카테고리의 다른 글
네이버 오픈 API Clova (0) | 2017.11.09 |
---|
댓글