Computer >> 컴퓨터 >  >> 프로그래밍 >> Android

Android 프래그먼트(Fragment)에서 findViewById를 사용하는 방법

프래그먼트에서 findViewById란?

이 예제는 프래그먼트(Fragment) 내부에서 findViewById() 메서드를 사용하는 방법을 보여줍니다. 액티비티(Activity)와 달리 프래그먼트에서는 뷰(View)에 접근하기 위해 반드시 뷰 계층 구조(root view)를 먼저 확보한 후, 해당 뷰 객체를 기준으로 findViewById를 호출해야 한다는 점이 핵심입니다.

아래 단계별 예제를 통해 두 개의 프래그먼트를 포함하는 화면을 만들고, 각 프래그먼트 안에서 TextView를 찾아오는 과정을 살펴보겠습니다.

1단계 — 새 프로젝트 생성

Android Studio에서 File ⇒ New Project로 이동하여 새 프로젝트를 생성하고, 필요한 모든 세부 정보를 입력합니다.

2단계 — activity_main.xml 작성

다음 코드를 res/layout/activity_main.xml 파일에 추가합니다.

<?xml version = "1.0" encoding = "utf-8"?>
<LinearLayout xmlns:android = "https://schemas.android.com/apk/res/android"
   android:orientation = "vertical"
   android:layout_width = "match_parent"
   android:layout_height = "match_parent">
   <LinearLayout
      android:id = "@+id/linearlayout01"
      android:layout_width = "fill_parent"
      android:layout_height = "fill_parent"
      android:background = "#ccc"
      android:layout_weight = "1"
      android:orientation = "vertical">
      <fragment android:name = "com.example.myapplication.FirstFragment"
         android:id = "@+id/frag_1"
         android:layout_width = "fill_parent"
         android:layout_height = "fill_parent" />
   </LinearLayout>
   <LinearLayout
      android:id = "@+id/linearlayout02"
      android:layout_width = "fill_parent"
      android:layout_height = "fill_parent"
      android:layout_weight = "1"
      android:background = "#eee"
      android:orientation = "vertical">
      <fragment android:name = "com.example.myapplication.SecondFragment"
         android:id = "@+id/frag_2"
         android:layout_width = "fill_parent"
         android:layout_height = "fill_parent" />
   </LinearLayout>
</LinearLayout>

위 코드에서는 화면을 상하로 나누어 두 개의 프래그먼트(FirstFragment, SecondFragment)를 배치했습니다. 각 프래그먼트는 layout_weight 속성으로 동일한 비율의 영역을 차지합니다.

3단계 — MainActivity.java 작성

다음 코드를 src/MainActivity.java 파일에 추가합니다.

import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
public class MainActivity extends FragmentActivity {
   @Override
   public void onCreate(Bundle savedInstanceState) {
      super.onCreate(savedInstanceState);
      setContentView(R.layout.activity_main);
   }
}

MainActivity는 별도의 로직 없이 위에서 작성한 레이아웃을 화면에 표시하는 역할만 수행합니다.

4단계 — FirstFragment.java 작성

다음 코드를 src/FirstFragment.java 파일에 추가합니다.

import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
public class FirstFragment extends Fragment {
   @Override
   public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
      ViewGroup root = (ViewGroup) inflater.inflate(R.layout.fragment, null);
      TextView but = (TextView) root.findViewById(R.id.text);
      return root;
   }
}

여기가 핵심 부분입니다. onCreateView()에서 inflater.inflate()로 생성된 루트 뷰(root)를 얻은 다음, root.findViewById(R.id.text)처럼 루트 뷰를 대상으로 findViewById를 호출해야 원하는 TextView를 정상적으로 찾을 수 있습니다. 액티비티처럼 곧바로 findViewById를 호출하면 NullPointerException이 발생할 수 있습니다.

5단계 — SecondFragment.java 작성

다음 코드를 src/SecondFragment.java 파일에 추가합니다.

import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
public class SecondFragment extends Fragment {
   TextView textView;
   View view;
   @Nullable
   @Override
   public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
      view = inflater.inflate(R.layout.fragment, container, false);
      return view;
   }
}

SecondFragment에서는 inflate 시 container와 false를 인자로 전달하는 방식을 사용했습니다. 이 방식이 null을 전달하는 것보다 권장되며, 이 경우 뷰를 찾으려면 view.findViewById(R.id.text) 형태로 호출하면 됩니다.

앱 실행 및 결과 확인

이제 애플리케이션을 실행해 보겠습니다. 실제 Android 모바일 기기가 컴퓨터에 연결되어 있다고 가정합니다. Android Studio에서 프로젝트의 액티비티 파일 중 하나를 열고 상단 툴바의 Run 아이콘을 클릭하세요. 실행 옵션에서 자신의 모바일 기기를 선택하면, 기기 화면에 아래와 같이 두 개의 프래그먼트가 배치된 기본 화면이 표시됩니다.

Android 프래그먼트(Fragment)에서 findViewById를 사용하는 방법

정리

프래그먼트에서 findViewById를 사용할 때 기억해야 할 핵심은 다음과 같습니다.

  • 반드시 onCreateView()에서 inflate한 뷰 객체를 통해 findViewById를 호출해야 합니다.
  • 루트 뷰를 변수에 저장한 후 root.findViewById(R.id.text) 형식으로 접근합니다.
  • inflate 시에는 (inflater, container, false)를 전달하는 방식이 권장됩니다.