빠르게배우는 안드로이드 Fragment-2(Activity-> Fragment로 쉽게 변경)

에 이어서 Fragment가 어떠한 것에서 activity와 유사한 코드를 가지는지 간략하게 알아보겠습니다.

앞서서 Fragment는 허니컴(3.x) 부터 등장한 기능인데요 2.3.x 진저브레드 버전등에서 호환이 되지 않는 문제가 있었습니다 .따라서 2.3.x 에 호환하기 위해서 supportV4라는 라이브러리를 통하여 Fragment를 사용할수있습니다.

프래그먼트는 엑티비티에서 파생되었기때문에 거의 유사한 구조를 가진다고 앞 강의의 배경에서 언급했었는데요

예를 들어 아래와같은 엑티비티가 있다고 생각해봅시다.
이 Activity코드를 Fragment로 변경하면 어떻게 될까요?

public class MainActivity extends AppCompatActivity {
    TextView textview;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        textview = (TextView)findViewById(R.id.xx);
        textview.setText("");
   }
}

우선 프래그먼트의 가장 기본적인 틀을 먼저보겠습니다.
Fragment에는 onCreate가 있고 onCreateView라는 메소드 부분이 존재합니다.

public class MainFragment extends Fragment {
 

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

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,Bundle savedInstanceState) {
        return inflater.inflate(R.layout.fragment_main, 
                                           container, 
                                              false);   
 }

onCreate 부분은 Fragment가 생성될때 호출되는 부분이고 onCreateView 는 onCreate 후에 화면을 구성할때 호출되는 부분입니다.

쉽게 생각해서 우리는 onCreate가 아닌 onCreateView부분에 Activity 에 onCreate 메소드 안에서 사용한 코드를 적으면 된다고 생각하면됩니다.

다음과 같이 코드를 변경할수있습니다.

public class MainFragment extends Fragment {
  TextView textview;
 
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
   
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,Bundle savedInstanceState) {
        
      View view = inflater.inflate(R.layout.fragment_main, 
                                              container, 
                                                 false);
       textview  =  (TextView)view.findViewById(R.id.xx);

거의 비슷하지만
LayoutInflater 를 통해서 layout xml을 가져오는것을 볼수있습니다. 이것 빼고는 엑티비티와 큰차이가 없죠?

(LayoutInflater에 대해 궁금하신분은 ListView강의를 먼저 선행하시면 되겠습니다.)

이제 다음강의에서 실제로 코딩을 진행해보도록하겠습니다. 다음강의로 이동해주세요..

//추가설명

아래의 자료를 보시고 혼란이 있으시다면 잊어버리셔도됩니다..

사실 onCreateView이외에 onViewCreated 라는 메소드 또한 존재합니다.

경축! 아무것도 안하여 에스천사게임즈가 새로운 모습으로 재오픈 하였습니다.
어린이용이며, 설치가 필요없는 브라우저 게임입니다.
https://s1004games.com

onCreateView

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {
    // Inflate the layout for this fragment
    return inflater.inflate(R.layout.fragment_main, container, false);
}

onViewCreated

@Override
public void onViewCreated(View view, Bundle savedInstanceState) {
    super.onViewCreated(view, savedInstanceState);
}

onViewCreated는 onCreateView에서 return해준 view 를 가지고 있습니다.

따라서 onCreate는 객체 생성이후 호출되고 onCreateView에서 inflater를 이용하여 view를 불러와서 view를 리턴(activity의 setContentView(R.layout.xx)) 부분이라고 생각하면되겠죠) 해서

onViewCreated는 이제 view.findViewById(R.id.xx)를 통해서 사용하는 것으로 설계가 되어있습니다.

하지만 본 강의에서는 onCreateView 안에서 findViewById로 xml과 연결하고 사용까지 하게되는데요

첫번째 이유는 대부분의 인터넷 예제들에서 onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) 함수에서 처리를 하는것이 대부분이라서 다른 자료와의 혼란을 막기위해서 본 강의에서도 onCreateView에서만 사용하게되었습니다.

두번째 이유는 안드로이드 스튜디오에서 Activity를 생성하는것처럼 Fragment를 생성할때 도움을 주는 기능이 있습니다. 이 기능을 사용하면

package me.jbne.fragmentexample;

import android.content.Context;
import android.net.Uri;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;


/**
 * A simple {@link Fragment} subclass.
 * Activities that contain this fragment must implement the
 * {@link MainFragment.OnFragmentInteractionListener} interface
 * to handle interaction events.
 * Use the {@link MainFragment#newInstance} factory method to
 * create an instance of this fragment.
 */
public class MainFragment extends Fragment {
    // TODO: Rename parameter arguments, choose names that match
    // the fragment initialization parameters, e.g. ARG_ITEM_NUMBER
    private static final String ARG_PARAM1 = "param1";
    private static final String ARG_PARAM2 = "param2";

    // TODO: Rename and change types of parameters
    private String mParam1;
    private String mParam2;

    private OnFragmentInteractionListener mListener;

    public MainFragment() {
        // Required empty public constructor
    }

    /**
     * Use this factory method to create a new instance of
     * this fragment using the provided parameters.
     *
     * @param param1 Parameter 1.
     * @param param2 Parameter 2.
     * @return A new instance of fragment MainFragment.
     */
    // TODO: Rename and change types and number of parameters
    public static MainFragment newInstance(String param1, String param2) {
        MainFragment fragment = new MainFragment();
        Bundle args = new Bundle();
        args.putString(ARG_PARAM1, param1);
        args.putString(ARG_PARAM2, param2);
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (getArguments() != null) {
            mParam1 = getArguments().getString(ARG_PARAM1);
            mParam2 = getArguments().getString(ARG_PARAM2);
        }
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        return inflater.inflate(R.layout.fragment_main, container, false);
    }

 

    // TODO: Rename method, update argument and hook method into UI event
    public void onButtonPressed(Uri uri) {
        if (mListener != null) {
            mListener.onFragmentInteraction(uri);
        }
    }

    @Override
    public void onAttach(Context context) {
        super.onAttach(context);
        if (context instanceof OnFragmentInteractionListener) {
            mListener = (OnFragmentInteractionListener) context;
        } else {
            throw new RuntimeException(context.toString()
                    + " must implement OnFragmentInteractionListener");
        }
    }

    @Override
    public void onDetach() {
        super.onDetach();
        mListener = null;
    }

    /**
     * This interface must be implemented by activities that contain this
     * fragment to allow an interaction in this fragment to be communicated
     * to the activity and potentially other fragments contained in that
     * activity.
     * <p/>
     * See the Android Training lesson <a href=
     * "http://developer.android.com/training/basics/fragments/communicating.html"
     * >Communicating with Other Fragments</a> for more information.
     */
    public interface OnFragmentInteractionListener {
        // TODO: Update argument type and name
        void onFragmentInteraction(Uri uri);
    }
}

위와 같은 코드가 나오게되는데요 이때도 기본적으로 onCreateView부분이 있지 onViewCreated는 보여지지 않습니다. 이 이유로 onCreateView 에서 코딩을 하는것이므로 양해 부탁드립니다.

 

[출처] https://medium.com/@henen/%EB%B9%A0%EB%A5%B4%EA%B2%8C%EB%B0%B0%EC%9A%B0%EB%8A%94-%EC%95%88%EB%93%9C%EB%A1%9C%EC%9D%B4%EB%93%9C-fragment-2-activity-fragment%EB%A1%9C-%EC%89%BD%EA%B2%8C-%EB%B3%80%EA%B2%BD-d0e0e3efd7

 

 

 

본 웹사이트는 광고를 포함하고 있습니다.
광고 클릭에서 발생하는 수익금은 모두 웹사이트 서버의 유지 및 관리, 그리고 기술 콘텐츠 향상을 위해 쓰여집니다.
번호 제목 글쓴이 날짜 조회 수
101 나인패치(Nine Patch) 이미지란? file 졸리운_곰 2020.10.10 56
100 Python으로 안드로이드 앱 만들기 졸리운_곰 2020.09.30 839
99 [Android] Fragment 를 이용한 탭 만들기 file 졸리운_곰 2020.09.19 52
98 빠르게배우는 안드로이드 Fragment-4(Fragment간 에 데이터전달) file 졸리운_곰 2020.09.19 36
97 빠르게배우는 안드로이드 Fragment-3(Fragment기초 실습) file 졸리운_곰 2020.09.19 58
» 빠르게배우는 안드로이드 Fragment-2(Activity-> Fragment로 쉽게 변경) 졸리운_곰 2020.09.19 38
95 빠르게배우는 안드로이드 Fragment -1 (배경) file 졸리운_곰 2020.09.19 38
94 안드로이드 스튜디오 - 새로 생성한 Activity Class를 쉽게 Manifest에 등록하기. file 졸리운_곰 2020.08.08 52
93 Android Studio Build시 failed linking references 해결방법 file 졸리운_곰 2020.05.05 517
92 [안드로이드 스튜디오] COULD NOT FIND COM.ANDROID.TOOLS.BUILD:GRADLE:3.0.0-BETA6 file 졸리운_곰 2020.05.05 43
91 Android Sync SQLite Database with Server using PHP and MySQL file 졸리운_곰 2019.02.25 7406
90 안드로이드의 MVC, MVP, MVVM 종합 안내서 file 졸리운_곰 2019.01.06 256
89 Getting Started: WebView-based Applications for Web Developers file 졸리운_곰 2018.09.03 264
88 App Inventor - MySQL interface 앱 인벤터 mysql 연결 file 졸리운_곰 2018.04.07 2330
87 Connect App Inventor to MySQL Database 앱 인벤터와 mysql 데이터베이스 연결 file 졸리운_곰 2018.04.07 5389
86 Create an API (PHP) 앱 인벤터와 php 통합 file 졸리운_곰 2018.04.07 493
85 Android WebView javascriptInterface 사용하기 file 졸리운_곰 2018.03.26 497
84 Using the WebViewer Control in App Inventor 앱인터에서 웹뷰 컨트롤 사용 file 졸리운_곰 2018.03.24 390
83 WebView Javascript Processor for App Inventor 앱 인벤터 웹뷰 자바스크립트 인터페이스 file 졸리운_곰 2018.03.24 365
82 android webview로 javascript 호출 및 이벤트 받기(연동하기) file 졸리운_곰 2018.03.19 1299
대표 김성준 주소 : 경기 용인 분당수지 U타워 등록번호 : 142-07-27414
통신판매업 신고 : 제2012-용인수지-0185호 출판업 신고 : 수지구청 제 123호 개인정보보호최고책임자 : 김성준 sjkim70@stechstar.com
대표전화 : 010-4589-2193 [fax] 02-6280-1294 COPYRIGHT(C) stechstar.com ALL RIGHTS RESERVED