|
안드로이드 개발 Fragment 와 Activity 의 통신하는 방법 |
|
환경: Android Studio |
Fragment 는 Activity 내에서 사용하는 인터페이스의 일부를 나타냅니다. 여러 개의 Fragment 를 하나의 Activity 에서 자유롭게 구성할 수 있으며, 다른 Activity 에서 재사용이 가능합니다. Fragment 는 Activity 안에서 사용할 수 있기 때문에 직접적으로 연결되어 있습니다. 오늘은 어떻게 Fragment 와 Activity 간의 연결 고리를 찾는지 알아 보겠습니다.
▼ 화면 상단에 버튼을 누르면 바로 아래에 있는 Fragment 에 포함된 TextView 의 글을 변경할 것입니다.
▼ 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");
}'안드로이드 개발' 카테고리의 다른 글
| 안드로이드 개발 Socket IO 사용해서 Node JS 서버와 통신하는 방법 (0) | 2018.11.06 |
|---|---|
| 안드로이드 개발 ERROR x86 emulation currently requires hardware acceleration 에러 (0) | 2018.10.17 |
| 안드로이드 개발 위젯 클릭(이벤트 연결) 으로 앱 실행하는 방법 (0) | 2018.09.21 |
| 안드로이드 개발 Fragment 화면 구성하는 방법 - FragmentActivity 로 화면 구성 (0) | 2018.09.18 |
| 안드로이드 개발 ArrayList 배열 개체를 JSON 으로 변경하는 방법 (1) | 2018.08.28 |
| 안드로이드 개발 간단하게 위젯 만드는 방법 (0) | 2018.08.15 |
| 안드로이드 개발 엑셀 파일 생성 및 데이터 불러오는 방법 (3) | 2018.08.07 |
| 안드로이드(Android) 개발 Timer 구현하는 방법 (0) | 2018.07.05 |
