티스토리 뷰

Android

Fragment 사용방법

세이브 2021. 9. 3. 13:12

 Fragment 배치 

 

1) Layout에 fragment 직접 배치

myfragment = getSupportFragmentManager().findFragmentById(R.id.myfragment)

 

 

2) Code상에서 fragment 추가 ( Layout에는 fragment를 배치할 frameLayout만 설정해놓는다. )

=> Trancsaction 사용!!(일괄처리)

FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
Ft.add(R.id.container,myfragment);
Ft.commit();

 

 

 

 

Fragment에 Tag설정

: fragment manager에 해당하는 fragment가 있는 지 확인(검색)할 때 사용된다.

 

1) Fragment에 tag를 설정하기

FragmentTransaction을 이용하여 add replace를 호출할 때 , 파라미터로 tag를 설정해 준다.

FragmentTransaction ft = getFragmentManager().beginTransaction();
ft.add(R.id.container , fragment , ”tag”);

 

2) FragmentManager를 이용하여 Tag를 가진 Fragment를 찾아올 수 있다.

Fragment f = getFragmentManager().findFragmentByTag(“tag”);

 

 

 

 

 fragment와 activity의 통신

1. Activity에서 Fragment로 값을 전달하는 방법

 

우선 값을 전달하는 객체가 있어야 한다. 그 객체가 바로 ‘Bundle’이다 !!

(bundle은 “키key (name) : 값value“ 형식으로 값을 저장한다. map과 유사형태)

 

 

 1 ) Fragment에 값을 전달하기 위해서는 bundle을 이용한다.

Bundle b = new Bundle( );
b.putString(“name”,”YSI”);

 

 

 2) 전달할 값을 저장한 Bundle을 Fragment의 setArguments( )로 fragment에 설정한다.

( setArguments()는 fragment가 fragment Manager에 추가되기 전에만 사용가능하다.)

Fragment f = new MyFragment();
f.setArguments(b);

 

3) Fragment는 getArguments() 를 이용하여 전달받은 Bundle을 얻어올 수 있다.

 

Bundle b = getArguments();
String name = b.getString(“name”);

 

 

 

2. Fragment에서 (fragment가 속한) Activity로 값을 전달하는 방법

 

1 ) getActivity( )를 이용한 값 전달. (fragment와 activity가 1:1 일 때 사용. 확장성이 떨어짐 )

 ((MainActivity)getActivity()).sendValue(10);

 

 

2)  fragment에 interface를 정의하고 Activity가 implements한 후 전달

 

Fragment에 값을 전달하기 위한 interface를 정의하고, Activity는 fragment의

interface를 implements한다.

 

- fragment는 activity를 가져와서 interface로 type casting한 후 값을 전달한다.

이 방법은 fragment를 사용하는 Activity가 여러 개 있을 경우 유용하다.

 

 

3) Fragment에서 (새로운) Activity를 호출하는 방법

 

startActivity()

-Fragment에도 startActivity()메소드가 있기 때문에 fragment의 startActivity()함수를 이용하여 구동.

// intent의 첫번째 인자는 context이다. 여기에 getContext()가 들어가도 된다.
Intent intent = new Intent(getActivity(), MyActivity.class);
startActivity(intent);

 

 

startActivityForResult()

- Fragment에서 startActivitiyForResult()를 호출하면 Activity가 호출되고 결과는 fragment에 있는 onActivityResult()로 수신한다.

 

Intent intent = new Intent (getActivity(), MyActivity.class );

startActivityForResult (intent, REQUEST_CODE_MY_ACTIVITY);

  Public void onActivityResult(int requestCode, int resultCode, Intent data){
    super.onActivityResult(requestCode,resultCode,data);
    
    if(requestCode == REQUEST_CODE_MY_ACTIVITY && resultCode == Activity.RESULT_OK){
      Toast.makeText(getActivity(),”Receive Data”,Toast.LENGTH_SHORT).show();
    }
}

참고 : https://recipes4dev.tistory.com/58

 

 

'Android' 카테고리의 다른 글

DataBinding  (0) 2021.09.03
콜백(Callback)과 리스너(Listener)  (0) 2021.09.03
Fragment  (0) 2021.09.03
Recycler View  (0) 2021.09.03
inflation  (0) 2021.09.03
공지사항
최근에 올라온 글
최근에 달린 댓글
Total
Today
Yesterday
링크
TAG
more
«   2025/03   »
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
글 보관함