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

안드로이드 프래그먼트에서 컨텍스트(Context)를 사용하는 방법

이 예제는 안드로이드 앱에서 프래그먼트(Fragment) 내부에서 컨텍스트(Context)를 사용하는 방법을 단계별로 보여줍니다.

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>

위 레이아웃에는 두 개의 프래그먼트(FirstFragmentSecondFragment)가 상하로 나뉘어 배치되어 있습니다.

3단계 — MainActivity.java 작성

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

package com.example.myapplication;
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);
    }
}

4단계 — FirstFragment.java 작성

src/FirstFragment.java 파일에 다음 코드를 추가합니다. 여기서 getActivity()를 호출하면 프래그먼트가 현재 연결된 액티비티의 컨텍스트를 얻을 수 있으며, 이 값을 텍스트뷰에 출력해 확인할 수 있습니다.

package com.example.myapplication;
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);
        but.setText(""+getActivity());
        return root;
    }
}

5단계 — SecondFragment.java 작성

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

package com.example.myapplication;
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;
    }
}

앱 실행 및 결과 확인

이제 애플리케이션을 실행해 보겠습니다. 실제 안드로이드 모바일 기기를 컴퓨터에 연결했다고 가정합니다. Android Studio에서 프로젝트의 액티비티 파일 중 하나를 연 뒤, 툴바의 Run(실행) 아이콘을 클릭하세요. 옵션 목록에서 자신의 모바일 기기를 선택하면, 기기 화면에 아래와 같은 기본 화면이 표시됩니다.

안드로이드 프래그먼트에서 컨텍스트(Context)를 사용하는 방법

참고: 프래그먼트에서 컨텍스트를 얻는 다양한 방법

프래그먼트 내부에서 컨텍스트가 필요할 때는 크게 세 가지 방법을 사용할 수 있습니다.

  • getActivity() — 프래그먼트가 연결된 액티비티를 반환합니다. 프래그먼트가 액티비티에 연결되지 않은 경우 null을 반환할 수 있으므로 주의해야 합니다.
  • getContext() — 프래그먼트가 현재 연결된 컨텍스트를 반환하며, 마찬가지로 null이 될 수 있습니다.
  • requireContext() — 컨텍스트가 반드시 존재해야 하는 경우 사용하며, 연결되어 있지 않으면 IllegalStateException이 발생합니다. 최신 AndroidX 환경에서 권장되는 방식입니다.