기본 콘텐츠로 건너뛰기

[Android] Fragment를 XML 코드로 생성하기

Android에서 Fragment는 무조건 Java Code로 FragmentTransaction을 통해 띄우는 건 줄 알았는데,
간단히 XML만으로도 띄울 수 있는 방법을 알게 되어 간단히 적어 본다.

1. Fragment를 상속받는 Class를 정의한다.


public class DetailsFragment extends Fragment {

    @BindView(R.id.tv_title) TextView mTvTitle;

    public DetailsFragment() {

    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View root = inflater.inflate(R.layout.fragment_details, container, false);
        ButterKnife.bind(this, root);
        return root;
    }
}

fragment_details.xml 은 생략한다.


2. 위에서 정의한 DetailsFragment를 적재할 MainActivity의 layout xml 코드를 아래와 같이 작성한다.


<LinearLayout 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"
        android:orientation="horizontal"
        tools:context="com.youknow.MainActivity">

    <fragment
android:name="com.youknow.DetailsFragment"
            android:id="@+id/details_fragment"
            android:layout_width="match_parent"
            android:layout_height="match_parent" />
</LinearLayout>


이렇게만 해주면, 자동으로 DetailsFragment가 MainActivity에 attach되어 동작하게 된다.
단 MainActivity는 FragmentActivity를 상속받아 구현한 Activity이어야 한다.
FragmentActivity의 서브 클래스인 AppCompatActivity도 가능하다.

fragment 태그의 name 속성에 우리가 띄우고자 하는 Fragment Class를 지정했는데,
Android Framework은 name 속성에 지정한 class를 찾아 인스턴스화하여 해당 위치에 attach한다.

댓글

이 블로그의 인기 게시물

[Android] Fragment 위에 Dialog 띄우기

배경:  - Fragment에 Google Maps를 올려 사용자에게 보여주고 있다.  - 사용자가 Dialog 창을 열어 검색을 할 수 있게 하고 싶다. 1. Dialog layout xml 생성 Dialog 창에는 하나의 EditText를 추가하여 사용자로 하여금 String을 입력받게 한다. 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 < LinearLayout   xmlns:android = "http://schemas.android.com/apk/res/android"         android:orientation = "vertical"         android:layout_width = "wrap_content"         android:layout_height = "wrap_content" >     < LinearLayout                 android:orientation = "horizontal"                 android:layout_width = "match_parent"                 android:layout_height = "wrap_content" >         < TextView                         android:layout_width = "match_parent"                         android:layout_height = "match_parent&quo

[Android] Fragment에 RecyclerView 추가하기

배경:  - List View를 보여주는 Fragment로 전환 RecyclerView  위젯은  ListView 의 업그레이드 버전으로 데이터 양이 많은 경우 스크롤을 효율적으로 수행할 수 있는 위젯이다. refer: http://developer.android.com/intl/ko/training/material/lists-cards.html 위 그림과 같이 Adapter를 통해 데이터에 접근하며,  LayoutManager를 통해 위젯 내부 항목들을 배치한다. 따라서 RecyclerView를 적용하기 위해서는     - LayoutManager     - Adaper 를 지정해주어야 한다. 1. 리스트에 보여질 각 항목 item layout 생성 다음과 같이 "id contents" 로 구성하였다. 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 < ?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&

미니 메추리 키우기 - 사육장 만들기

미니 메추리는 우리가 알고 있는 일반 메추리보다 조금 작은 개체입니다. 버튼퀼(버튼퀘일)이라고도 불리죠. 일반 메추리보다 작기도 하고 짝이 맞는 암수가 같이 있으면 그리 시끄럽지도 않습니다. 여러 모로 키우기가 좀더 수월하죠. 첫 번째 단계로 먼저 아이들이 지낼 집을 만들어 주었습니다. 사실 여러 고민을 많이 했어요 지금 소개하는 집을 만들기 전에는 120L 짜리 대형 리빙 박스로 집을 만들어 주었었죠. 값이 저렴하고 개량하는 것이 크게 어렵지 않기 때문에 많은 분들이 리빙 박스를 개조하여 집을 만들어 주고 있어요. 저 같은 경우는 보온을 생각해서 안쪽에는 단열재를 덧대기도 했죠. 하지만 사실 리빙 박스로 집을 만드는게 아주 쉽지만은 않아요. 물론 있는 그대로를 사용하신다면 어려울 건 전혀 없죠. 그런데 만약 전구를 달기 위해 구멍을 뚫거나, 환기 구멍을 뚫거나 기타 여러 필요에 의해 리빙 박스를 뜯어 고쳐야 한다면 이야기가 달라지죠. 저도 사실 이런 불편함에 고민고민을 하다가 오늘 소개해 드릴 두 번째 집과 같은 것을 생각하게 되었어요. 바로 시중에서 쉽게 구할 수 있는 종이 박스를 활용한 것인데요. 위쪽 뚜껑에는 구멍을 두 개를 뚫었어요. 작은 구멍은 온도 조절을 위한 전구 바로 위쪽으로 온도가 너무 올라갈 경우 온도 조절을 위해 뚫어 놓았고요.  아래 좀더 큰 구멍은 물, 먹이 등을 교체해주기 위한 구멍이에요.  정면에는 창을 내어 관찰할 수 있게 했어요. 지금은 저 가운데도 잘라내서 크게 창 하나로 만들었어요. 안쪽에는 온도계를 비치하여 내부 온도를 확인할 수 있게 해두었습니다. (지금 생각해보니 전구 바로 아래쪽에 위치한 탓에 제대로 된 온도 측정이 될지 모르겠네요;;;) 그리고 보셔서 아시겠지만, 내부 바닥, 옆면에 단