차근차근/Android
android actionbar + fragmant
ActionBar 로 Tab만들기
http://coolkim.tistory.com/343
Implementing ActionBarSherlock Fragment Tabs in Android
http://www.androidbegin.com/tutorial/implementing-actionbarsherlock-fragment-tabs-in-android/
In this tutorial, you will learn how to implement ActionBarSherlock fragment tabs in your Android application. Tabs allow user to navigate among sibling screens by selecting the appropriate tab indicator available at the top of the display. We will create tabs that allow users to navigate between fragments that contain a particular text using ActionBarSherlock Library. So lets begin…
Prepare your project by importing the ActionBarSherlock Library. Refer to Implementing ActionBarSherlock in Android tutorial.
Create a new project in Eclipse File > New > Android Application Project. Fill in the details and name your project ABSFragmentTabs.
Application Name : ABSFragmentTabs
Project Name : ABSFragmentTabs
Package Name : com.androidbegin.absfragmenttabs
Open your MainActivity.java and paste the following code.
MainActivity.java
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 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 | package com.androidbegin.absfragmenttabs; import com.actionbarsherlock.app.ActionBar; import com.actionbarsherlock.app.SherlockFragmentActivity; import android.os.Bundle; import android.support.v4.app.Fragment; public class MainActivity extends SherlockFragmentActivity { ActionBar.Tab Tab1,Tab2,Tab3; Fragment fragmentTab1 = new FragmentTab1(); Fragment fragmentTab2 = new FragmentTab2(); Fragment fragmentTab3 = new FragmentTab3(); @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); ActionBar actionBar = getSupportActionBar(); // Hide Actionbar Icon actionBar.setDisplayShowHomeEnabled(false); // Hide Actionbar Title actionBar.setDisplayShowTitleEnabled(false); // Create Actionbar Tabs actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS); // Set Tab Icon and Titles Tab1 = actionBar.newTab().setIcon(R.drawable.tab1); Tab2 = actionBar.newTab().setText("Tab2"); Tab3 = actionBar.newTab().setText("Tab3"); // Set Tab Listeners Tab1.setTabListener(new TabListener(fragmentTab1)); Tab2.setTabListener(new TabListener(fragmentTab2)); Tab3.setTabListener(new TabListener(fragmentTab3)); // Add tabs to actionbar actionBar.addTab(Tab1); actionBar.addTab(Tab2); actionBar.addTab(Tab3); } } |
We have created three tabs with tab listeners and set the action bar to navigation mode tabs. For the first tab, we have set a custom tab icon and the other two with texts title. We have prepared a sample tab icon for this tutorial. Insert your downloaded sample tab icon into your res > drawable-hdpi.
Sample Tab Icon
Next, create an XML graphical layout for the MainActivity. Go to res > layout > Right Click on layout > New > Android XML File
Name your new XML file activity_main.xml and paste the following code.
activity_main.xml
1 2 3 4 5 | <?xml version="1.0" encoding="utf-8"?> <FrameLayout xmlns:android="http://schemas.android.com/apk/res/android" android:id="@+id/fragment_container" android:layout_width="match_parent" android:layout_height="match_parent" /> |
Next, create a tab listener class. Go to File > New > Class and name it TabListener.java. Select your package named com.androidbegin.absfragmenttabs and click Finish.
Open your TabListener.java and paste the following code.
TabListener.java
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 31 32 33 34 35 | package com.androidbegin.absfragmenttabs; import com.actionbarsherlock.app.ActionBar; import com.actionbarsherlock.app.ActionBar.Tab; import android.support.v4.app.Fragment; import android.support.v4.app.FragmentTransaction; public class TabListener implements ActionBar.TabListener { Fragment fragment; public TabListener(Fragment fragment) { // TODO Auto-generated constructor stub this.fragment = fragment; } @Override public void onTabSelected(Tab tab, FragmentTransaction ft) { // TODO Auto-generated method stub ft.replace(R.id.fragment_container, fragment); } @Override public void onTabUnselected(Tab tab, FragmentTransaction ft) { // TODO Auto-generated method stub ft.remove(fragment); } @Override public void onTabReselected(Tab tab, FragmentTransaction ft) { // TODO Auto-generated method stub } } |
This tab listener class manages the selected tab clicks and to show or remove a fragment.
Next, create the first fragment tab. Go to File > New > Class and name it FragmentTab1.java. Select your package named com.androidbegin.absfragmenttabs and click Finish.
Open your FragmentTab1.java and paste the following code.
FragmentTab1.java
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 | package com.androidbegin.absfragmenttabs; import android.os.Bundle; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import com.actionbarsherlock.app.SherlockFragment; public class FragmentTab1 extends SherlockFragment { @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View rootView = inflater.inflate(R.layout.fragmenttab1, container, false); return rootView; } } |
Next, create the second fragment tab. Go to File > New > Class and name it FragmentTab2.java. Select your package named com.androidbegin.absfragmenttabs and click Finish.
Open your FragmentTab2.java and paste the following code.
FragmentTab2.java
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 | package com.androidbegin.absfragmenttabs; import android.os.Bundle; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import com.actionbarsherlock.app.SherlockFragment; public class FragmentTab2 extends SherlockFragment { @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View rootView = inflater.inflate(R.layout.fragmenttab2, container, false); return rootView; } } |
Next, create the third fragment tab. Go to File > New > Class and name it FragmentTab3.java. Select your package named com.androidbegin.absfragmenttabs and click Finish.
Open your FragmentTab3.java and paste the following code.
FragmentTab3.java
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 | package com.androidbegin.absfragmenttabs; import android.os.Bundle; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import com.actionbarsherlock.app.SherlockFragment; public class FragmentTab3 extends SherlockFragment { @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View rootView = inflater.inflate(R.layout.fragmenttab3, container, false); return rootView; } } |
Next, create an XML graphical layout for first fragment tab. Go to res > layout > Right Click on layout > New > Android XML File
Name your new XML file fragmenttab1.xml and paste the following code.
fragmenttab1.xml
1 2 3 4 5 6 7 8 9 10 11 12 13 | <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" > <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_centerHorizontal="true" android:layout_centerVertical="true" android:text="@string/Fragmenttab1"/> </RelativeLayout> |
Next, create an XML graphical layout for second fragment tab. Go to res > layout > Right Click on layout > New > Android XML File
Name your new XML file fragmenttab2.xml and paste the following code.
fragmenttab2.xml
1 2 3 4 5 6 7 8 9 10 11 12 13 | <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" > <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_centerHorizontal="true" android:layout_centerVertical="true" android:text="@string/Fragmenttab2"/> </RelativeLayout> |
Next, create an XML graphical layout for third fragment tab. Go to res > layout > Right Click on layout > New > Android XML File
Name your new XML file fragmenttab3.xml and paste the following code.
fragmenttab3.xml
1 2 3 4 5 6 7 8 9 10 11 12 13 | <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" > <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_centerHorizontal="true" android:layout_centerVertical="true" android:text="@string/Fragmenttab3"/> </RelativeLayout> |
Change the application name and fragment textview texts in strings.xml. Open your strings.xml and paste the following code. Go to res > values > strings.xml
strings.xml
1 2 3 4 5 6 7 8 9 10 | <resources> <string name="app_name">ABS Fragment Tabs</string> <string name="hello_world">Hello world!</string> <string name="menu_settings">Settings</string> <string name="Fragmenttab1">This is ActionBarSherlock Fragment 1</string> <string name="Fragmenttab2">This is ActionBarSherlock Fragment 2</string> <string name="Fragmenttab3">This is ActionBarSherlock Fragment 3</string> </resources> |
In your AndroidManifest.xml, we need to change the theme style to “Theme.Sherlock” and set your preferable Android minimum SDK version. Open your AndroidManifest.xml and paste the following code.
AndroidManifest.xml
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 | <manifest xmlns:android="http://schemas.android.com/apk/res/android" package="com.androidbegin.absfragmenttabs" android:versionCode="1" android:versionName="1.0" > <uses-sdk android:minSdkVersion="1" android:targetSdkVersion="15" /> <application android:icon="@drawable/ic_launcher" android:label="@string/app_name" android:theme="@style/Theme.Sherlock" > <activity android:name=".MainActivity" > <intent-filter> <action android:name="android.intent.action.MAIN" /> <category android:name="android.intent.category.LAUNCHER" /> </intent-filter> </activity> </application> </manifest> |
Output :
Source Code
[ActionBar] Tab 만들기
http://heroinekyo.tistory.com/entry/ActionBar-Tab-%EB%A7%8C%EB%93%A4%EA%B8%B0
기존의 GB 이하의 버전에서는 TabActivity를 통해 ViewGroup으로 Tab을 생성 및 관리를 했었다.
하지만 ICS부터는 위의 방법보다 ActionBar와 Fragment를 이용해 Tab을 구성하기를 권한다.
이전 포스팅에서 ActionBar를 이용한 간단한 Tab을 구현하는 방법을 작성해 봤지만, 이는 각 Tab이 항상 같은 구조(같은 화면)을 갖는 다는 조건이 붙는다. (Tab마다 화면이 같다면 Tab이 있을 필요가 있을까?ㅎㅎ)
3개의 TAb을 만든다는 가정하에 아래 소스를 작성했다.
ActionBar에 Tab을 등록한다. |
1. 현재 Activity의 ActionBar 레퍼런스를 받아온다. 2. ActionBar를 Navigation Mode로 설정한다. 3. ActionBar에 Tab에 관련된 리스너를 등록하고, 각 Tab에 들어갈 Fragment를 설정한다. |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 | ActionBar actionBar = getActionBar(); actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS); actionBar.setDisplayOptions(ActionBar.DISPLAY_SHOW_TITLE, ActionBar.DISPLAY_SHOW_TITLE); actionBar.addTab(actionBar.newTab() .setText( "tab1" ) .setTabListener( new FragmentTabListener<tab1>( this , "tab1" , Tab1. class ))); actionBar.addTab(actionBar.newTab() .setText( "tab2" ) .setTabListener( new FragmentTabListener<tab2>( this , "tab2" , Tab2. class ))); actionBar.addTab(actionBar.newTab() .setText( "tab3" ) .setTabListener( new FragmentTabListener<tab3>( this , "tab3" , Tab3. class ))); if (savedInstanceState != null ){ actionBar.setSelectedNavigationItem(savedInstanceState.getInt( "tab" , 0 )); } </tab3></tab2></tab1> |
또한 안드로이드는 onSaveInstanceState()
에 현재 SeletedTab 정보를 입력하기를 권장한다.
1 2 3 4 5 6 | @Override protected void onSaveInstanceState(Bundle outState) { // TODO Auto-generated method stub super .onSaveInstanceState(outState); outState.putInt( "tab" , getActionBar().getSelectedNavigationIndex()); } |
TabListener를 구성한다. |
1. 생성자에서 Tag를 통해 Fragment를 찾고 Activity에 attach되어 있다면 detach를 실행한다. 즉, 최소 생성될 때는 모든 Fragment는 Activity에서 detach되어져야 하고, null이어야 한다. 나중에 Seleted된 Fragment만이 attach될 수 있다. 2. onTabUnselected에 선택이 해제되는 Fragment에 대해 deatch해준다. 3. onTabSelected 선택된 Fragment에 대해 FragmentTransaction을 통해 add를 하거나 이미 생성된 적이 있다면 attach를 시켜준다. 메소드는 onTabUnselected -> onTabSelected 순으로 실행된다. |
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 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 | import android.app.ActionBar.Tab; import android.app.ActionBar.TabListener; import android.app.Activity; import android.app.Fragment; import android.app.FragmentManager; import android.app.FragmentTransaction; import android.os.Bundle; import android.util.Log; import android.widget.Toast; public class FragmentTabListener <t extends = "" fragment= "" > implements TabListener{ public static final String TAG = "FragmentTabListener" ; private final Activity mActivity; private final String mTag; private final Class<t> mClass; private final Bundle mBundle; private Fragment mFragment; public FragmentTabListener(Activity mActivity, String mTag, Class<t> mClass) { this (mActivity, mTag, mClass, null ); } public FragmentTabListener(Activity mActivity, String mTag, Class<t> mClass, Bundle mBundle) { super (); this .mActivity = mActivity; this .mTag = mTag; this .mClass = mClass; this .mBundle = mBundle; FragmentManager fm = this .mActivity.getFragmentManager(); mFragment = fm.findFragmentByTag(mTag); if (mFragment != null && !mFragment.isDetached()){ FragmentTransaction ft = this .mActivity.getFragmentManager().beginTransaction(); ft.detach(mFragment); ft.commit(); } } @Override public void onTabSelected(Tab tab, FragmentTransaction ft) { // TODO Auto-generated method stub Log.e(TAG, "onTabSelected" ); if (mFragment == null ){ mFragment = Fragment.instantiate(mActivity, mClass.getName(), mBundle); ft.add(android.R.id.content, mFragment, mTag); } else { ft.attach(mFragment); } } @Override public void onTabUnselected(Tab tab, FragmentTransaction ft) { // TODO Auto-generated method stub Log.e(TAG, "onTabUnselected" ); if (mFragment != null ){ ft.detach(mFragment); } } @Override public void onTabReselected(Tab tab, FragmentTransaction ft) { // TODO Auto-generated method stub Toast.makeText(mActivity, "ReSelected!!!" , Toast.LENGTH_SHORT).show(); } } </t></t></t></t>
* <t extends = "" fragment= "" > 여기에 계속 빨간줄 생겨서 t extends Fragment 로 바꿈 * setTabListener( new FragmentTabListener<tab1>( this , "tab1" , Tab1. class )) 는 fragment class만들고 파일명 써줌 setTabListener( new FragmentTabListener< fragment1>( this , "tab1" , fragment1. class )) |
근데 액션바를 나는 하단에 놨는데.. 이걸 원한게 아닌데.. 어떻게 수정하지?
'차근차근 > Android' 카테고리의 다른 글
모바일 웹 가로 고정 (0) | 2015.02.13 |
---|---|
FragmentTab | Fragment example (0) | 2015.02.11 |
webview , asset , font (0) | 2015.02.06 |
actionbar + navigation drawer 소스 (0) | 2015.02.04 |
Navigation Drawer 분석 (0) | 2015.02.04 |
'차근차근/Android'의 다른글
- 현재글android actionbar + fragmant