빠르게배우는 안드로이드 Fragment-2(Activity-> Fragment로 쉽게 변경) :: 안드로이드 설치 및 개발[SSISO Community]
 
SSISO 카페 SSISO Source SSISO 구직 SSISO 쇼핑몰 SSISO 맛집
추천검색어 : JUnit   Log4j   ajax   spring   struts   struts-config.xml   Synchronized   책정보   Ajax 마스터하기   우측부분

안드로이드 설치 및 개발
[1]
등록일:2018-07-25 15:12:46 (0%)
작성자:
제목:빠르게배우는 안드로이드 Fragment-2(Activity-> Fragment로 쉽게 변경)
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);
    return view;

 }

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

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

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

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

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

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 에서 코딩을 하는것이므로 양해 부탁드립니다.

[본문링크] 빠르게배우는 안드로이드 Fragment-2(Activity-> Fragment로 쉽게 변경)
[1]
코멘트(이글의 트랙백 주소:/cafe/tb_receive.php?no=34753
작성자
비밀번호

 

SSISOCommunity

[이전]

Copyright byCopyright ⓒ2005, SSISO Community All Rights Reserved.