2013년 6월 27일 목요일

FragmentActivity, FragmentTabHost 사용하기

이전 블로그에서 이전 함 (원본 글 2013/06/27 작성)

아래 처럼 FragmentTabHost를 사용하면서 이것저것 하려니 개고생 함..
그냥 Android Project를 하나 만들고 MainActivity를 만들때 Navigation Type을 Scrollable Tabs+Swipe로 선택하여
SectionPagerAdapter + FragmentActivity 예제를 만들어 참고하여 app 만드는게 편함..


--------------------------------------------------------------------------------------------------

TabActivity가 deprecated 되면서 FragmentActivity & FragmentTabHost를 사용하게 되어
보던 중 생각보다 Google documentation이 부실해서 여기저기 찾아보고 정리함.

[Android Support Libraries 다운로드 및 설치]

> 아래 처럼 Android SDK Manager를 통해서 다운로드 하고 개발중인 project의 lib에 복사하고 project libraries로 추가

 Downloading the Support Package

The Support Package is provided as a downloadable package from the Android SDK Manager. To install:
  1. Launch the Android SDK Manager.
    From Eclipse, you can select Window > Android SDK Manager. Or, launch SDK Manager.exe from the <sdk>/ directory (on Windows only) or android from the <sdk>/tools/ directory.
  2. Expand the Android Repository, check Android Support package and click Install selected.
  3. Proceed to install the package.
When done, all files (including source code, samples, and the JAR files) are saved into the<sdk>/extras/android/support/ directory. This directory contains each of the different support libraries, such as the library for API level 4 and up and the library for API level 13 and up, each named with the respective version (such as v4/).

Setting Up a Project to Use a Library


To add one of the libraries to your Android project:

Add the JAR file to your project.
Copy the JAR file for the library you want to use into your Android project. To do this:

  • Create the directory libs/ at the root of your project (next to src/, res/, and so forth).
  • Locate the JAR file for the library you want to use and copy it into the libs/ directory.
    For example, the library that supports API level 4 and up is located at <sdk>/extras/android/support/v4/android-support-v4.jar.
Your build system may expect to find the JAR file in a directory other than libs. Read the documentation for your build system to learn where to put the JAR file.

<dl style="color: rgb(34, 34, 34); font-family: Roboto, sans-serif; font-size: 14px; line-height: 19px; background-color: rgb(249, 249, 249);">
If necessary, add the libs/ directory to your build path.
Read the documentation for your build system to learn how to add the JAR file to the build path.
</dl>


[Fragment 개념] 
> Fragment에 대한 전반적인 tutorial.. 추천

[FragmentTabHost reference]

> 사실 아래 예제가 다임.. 좀 더 자세한 설명은 아래 링크를 참고. 
   TabHost.addTab() 에서 class들은 Fragment를 상속받아 만든 class 들임.

 Here is a simple example of using a FragmentTabHost in an Activity:
import com.example.android.supportv4.R;
import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentTabHost;
/**
 * This demonstrates how you can implement switching between the tabs of a
 * TabHost through fragments, using FragmentTabHost.
 */
public class FragmentTabs extends FragmentActivity {
    private FragmentTabHost mTabHost;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        setContentView(R.layout.fragment_tabs);
        mTabHost = (FragmentTabHost)findViewById(android.R.id.tabhost);
        mTabHost.setup(this, getSupportFragmentManager(), R.id.realtabcontent);

        mTabHost.addTab(mTabHost.newTabSpec("simple").setIndicator("Simple"),
                FragmentStackSupport.CountingFragment.class, null);
        mTabHost.addTab(mTabHost.newTabSpec("contacts").setIndicator("Contacts"),
                LoaderCursorSupport.CursorLoaderListFragment.class, null);
        mTabHost.addTab(mTabHost.newTabSpec("custom").setIndicator("Custom"),
                LoaderCustomSupport.AppListFragment.class, null);
        mTabHost.addTab(mTabHost.newTabSpec("throttle").setIndicator("Throttle"),
                LoaderThrottleSupport.ThrottledLoaderListFragment.class, null);
    }
}
This can also be used inside of a fragment through fragment nesting:
import com.example.android.supportv4.R;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentTabHost;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
public class FragmentTabsFragmentSupport extends Fragment {
    private FragmentTabHost mTabHost;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
            Bundle savedInstanceState) {
        mTabHost = new FragmentTabHost(getActivity());
        mTabHost.setup(getActivity(), getChildFragmentManager(), R.id.fragment1);

        mTabHost.addTab(mTabHost.newTabSpec("simple").setIndicator("Simple"),
                FragmentStackSupport.CountingFragment.class, null);
        mTabHost.addTab(mTabHost.newTabSpec("contacts").setIndicator("Contacts"),
                LoaderCursorSupport.CursorLoaderListFragment.class, null);
        mTabHost.addTab(mTabHost.newTabSpec("custom").setIndicator("Custom"),
                LoaderCustomSupport.AppListFragment.class, null);
        mTabHost.addTab(mTabHost.newTabSpec("throttle").setIndicator("Throttle"),
                LoaderThrottleSupport.ThrottledLoaderListFragment.class, null);

        return mTabHost;
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        mTabHost = null;
    }
}

[FragTabHost 사용 상세 예제들]

> 모든 코드(Fragment classes) 포함

> 좀 자세한 설명

[FragTabs를 아래로 위치시키기]

> 웹상에서는 Relative를 사용하거나 Linear의 weight를 사용하는 방법 아니면 Custom tab을 사용하는 방법이 있지만 위에서는 간단하게 해결 함. 아래는 살짝 수정한 코드
 <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    android:weightSum="1" >

    <FrameLayout
        android:id="@+id/realtabcontent"
        android:layout_width="match_parent"
        android:layout_height="0dip"
        android:layout_weight="1" />

    <android.support.v4.app.FragmentTabHost
        android:id="@android:id/tabhost"
        android:layout_width="match_parent"
        android:layout_height="wrap_content" >

        <FrameLayout
            android:id="@android:id/tabcontent"
            android:layout_width="0dp"
            android:layout_height="0dp" />

        <TabWidget
            android:id="@android:id/tabs"
            android:layout_width="fill_parent"
            android:layout_height="wrap_content" />
    </android.support.v4.app.FragmentTabHost>

</LinearLayout>


[Fragment Tab 간 data 전달]
> Android Developers site의 Fragment 관련 내용에서 나오는 내용.

> 좀 더 상세한 내용, 사실 Fragment의 Tag를 알아내는 방법을 몰라 좀 고생했었음.
   Activity에 Tag를 받는 함수를 만들고 각 Fragment Tab이 생성 되었을 때 Activity의 함수를 통해 Tag을 등록
   좀 나이스 한 방법은 아니지만.. 일단 뭐...
 public class MyFragmentB extends Fragment {

 TextView b_received;
 
 @Override
 public View onCreateView(LayoutInflater inflater, ViewGroup container,
   Bundle savedInstanceState) {
  View myFragmentView = inflater.inflate(R.layout.fragment_b, container, false);
  
  b_received = (TextView)myFragmentView.findViewById(R.id.b_received);
  String myTag = getTag();
  
  ((AndroidViewPagerActivity)getActivity()).setTabFragmentB(myTag);


[기타]
> 코드가 좀 이상하네...

댓글 없음:

댓글 쓰기