Please Enable JavaScript!
Gon[ Enable JavaScript ]

안드로이드 개발 Fragment 와 Activity 의 통신하는 방법

안드로이드 개발
반응형

안드로이드 개발 Fragment Activity 의 통신하는 방법

 

환경: Android Studio

 

Fragment Activity 내에서 사용하는 인터페이스의 일부를 나타냅니다. 여러 개의 Fragment 를 하나의 Activity 에서 자유롭게 구성할 수 있으며, 다른 Activity 에서 재사용이 가능합니다. Fragment Activity 안에서 사용할 수 있기 때문에 직접적으로 연결되어 있습니다. 오늘은 어떻게 Fragment Activity 간의 연결 고리를 찾는지 알아 보겠습니다.

 

화면 상단에 버튼을 누르면 바로 아래에 있는 Fragment 에 포함된 TextView 의 글을 변경할 것입니다.

안드로이드 개발 Fragment 와 Activity 의 통신하는 방법

 

Activity 에 있는 버튼 클릭 이벤트 함수는 다음과 같습니다. Fragment 객체를 가져오기 위해서는 getSupportFragmentManager() 함수를 사용해야 합니다. findFragmentById() 로 접근하고 싶은 레이아웃 객체의 인스턴스를 가져옵니다.

// 버튼을 클릭하면 Fragment 의 Text 를 변경한다.
public void onFragmentChange(View v){
    OneFragment oneFragment =
            (OneFragment) getSupportFragmentManager().findFragmentById(R.id.fg_one);

    oneFragment.setTextChange("change text");
}

 

다음은 화면 전체를 구성하는 MainActivity 의 레이아웃 XML 입니다.

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <Button
        android:id="@+id/btn_change"
        android:text="Change Fragment Text"
        android:layout_width="match_parent"
        android:layout_height="0dp"
        android:layout_weight="1"
        android:onClick="onFragmentChange"/>
    
    <fragment android:name="gon.com.fragment.OneFragment"
        android:id="@+id/fg_one"
        android:layout_weight="4"
        android:layout_width="match_parent"
        android:layout_height="0dp" />

    <fragment android:name="gon.com.fragment.TwoFragment"
        android:id="@+id/fg_two"
        android:layout_weight="5"
        android:layout_width="match_parent"
        android:layout_height="0dp" />

</LinearLayout>

 

Activity 의 전체 소스입니다.

import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;

public class MainActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
    }

    // 버튼을 클릭하면 Fragment 의 Text 를 변경한다.
    public void onFragmentChange(View v){
        OneFragment oneFragment =
                (OneFragment) getSupportFragmentManager().findFragmentById(R.id.fg_one);

        oneFragment.setTextChange("change text");
    }
}

 

상단에 있는 Fragment 를 상속받아 구현한 OneFragment 의 소스입니다. Activity 에서 호출한 setTextChange() 함수에 TextView 의 값을 변경합니다.

import android.os.Bundle;
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.Button;
import android.widget.TextView;

import java.io.FileDescriptor;
import java.io.PrintWriter;

public class OneFragment extends Fragment{

    //View mView;
    TextView mTv;

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

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_one,null);
        mTv =  view.findViewById(R.id.tv_one);
        return view;
    }

    @Override
    public void onPause() {
        super.onPause();
    }

    @Override
    public void dump(String prefix, FileDescriptor fd, PrintWriter writer, String[] args) {
        super.dump(prefix, fd, writer, args);
    }

    public void setTextChange(String text){
        mTv.setText(text);
    }

    public void setActivityChange(){
        Button btn = (Button)getActivity().findViewById(R.id.btn_change);
        btn.setText("button change");
    }
}

 

반대로 Fragment 에서 Activity 를 참조하고 싶다면 getActivity() 함수를 사용합니다.

public void setActivityChange(){
    Button btn = (Button)getActivity().findViewById(R.id.btn_change);
    btn.setText("button change");
}


반응형
Posted by 녹두장군1
,