본문 바로가기
수업내용

20230726 Android Fragment

by titlejjk 2023. 7. 26.

새로운 모듈을 만들어주었다.

모듈의 이름은 Fragment

 

Fragment(이하 프래그먼트)는

FragmentActivity내의 어떤 동작 또는 사용자 인터페이스의 일부를 나타낸다. 여러 개의 프래그먼트를 하나의 액티비티에 결합하여 창이 여러 개인 UI를 빌드할 수 있다.

 

위와 같은 경우에 프래그먼트를 사용하지 않았을 경우에는 내용물을 제외한 기본적인 틀을 복사해서 사용해야 겠지만

프래그먼트를 이용하면 프래그먼트 하나를 통해 여러개의 Activity에서 사용할 수 있게 된다.

화면이 전환이 될때 하나의 Activity의 여러개의 프래그먼트를 사용해서

클라이언트가 느낄 때에는 전체적인 화면이 전환되는 느낌이 들지만 실은 프래그먼트만 바뀌게 해서 화면전환이 되는 것 처럼 사용할 수도 있다.

 

사용방법👉👉👉

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity"
    android:orientation="vertical">
    <fragment
        android:layout_width="match_parent"
        android:layout_height="200dp"
        android:name="com.example.step05fragment.MyFragment"
        android:id="@+id/fragment1"/>
    <Button
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="Reset"/>
</LinearLayout>

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity"
    android:orientation="vertical">
    <fragment
        android:layout_width="match_parent"
        android:layout_height="200dp"
        android:name="com.example.step05fragment.MyFragment"
        android:id="@+id/fragment1"/>
    <Button
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:textSize="100dp"
        android:text="😎"
        android:id="@+id/resetBtn"/>
    <fragment
        android:layout_width="match_parent"
        android:layout_height="300dp"
        android:name="com.example.step05fragment.MyFragment"
        android:id="@+id/fragment2"/>
</LinearLayout>
package com.example.step05fragment;

import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;

/*
    [Fragment]

    - 액티비티의 제어하에 존재하는 mini Controller
    - 재활용을 염두에 두고 만드는 경우가 많다
    - 재활용이라는 것은 여러개의 액티비티에서 활용된다는 의미

    [ Fragment 만드는 방법 ]
    1. Fragment 클래스를 상속 받는다.
    2. 프레그먼트의 layout xml 문서를 만든다.
    3. onCreateView() 메소드를 오버라이딩 한다.
*/
public class MyFragment extends Fragment implements View.OnClickListener{
    TextView textView;
    //해당 프레그먼트가 제어할 View 객체를 만들어서 리턴해주는 메소드
    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        //1. fragment_my.xml 문서를 전개해서 View 를 만든다음
        View view=inflater.inflate(R.layout.fragment_my, container, false);
        //만든 View 객체에서 TextView 의 참조값을 얻어낸다
        textView=view.findViewById(R.id.textView);
        //TextView 에 OnClick 리스너를 등록한다.
        textView.setOnClickListener(this);
        //2. 해당 View 를 리턴해 준다.
        return view;
    }

    @Override
    public void onClick(View view) {
        //TextView 에 출력한 문자열을 숫자로 바꿔서 얻어낸다.
        int count=Integer.parseInt(textView.getText().toString());
        //count 를 1 증가 시킨다.
        count++;
        //TextView 에 문자열로 바꿔서 출력한다.
        textView.setText(Integer.toString(count));
    }
    //Activity에서 특정 시점에 호출 할 메서드
    public void reset(){
        textView.setText("0");
    }
}

 

 

프레그먼트의 참조값은 어떻게 얻을까?

 

우선 프레그먼트의 참조값을 얻으려는 이유는 reset버튼(reset( )메서드 사용을 하기 위해)을 프레그먼트에 적용하기 위해서인데 프레그먼트는 view가 아니기에

다른 방법으로 프레그먼트의 참조값을 얻어와야한다.

 

package com.example.step05fragment;

import androidx.appcompat.app.AppCompatActivity;

import android.os.Bundle;
import android.widget.Button;

public class MainActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        //activity_main.xml문서에 <fragment>요소가 있다. 해당 프레그먼트의 참조값은 어떻게 얻어낼까?
        setContentView(R.layout.activity_main);

        
        //리셋 버튼에 리스너 등록하기
        Button resetBtn = findViewById(R.id.resetBtn);
    }
}

여기에서 프레그먼트의 객체를 얻어오는 코드를 추가해 보겠다.

 

먼저 FragmentManager의 객체를 얻어온다.

//FragmentManager객체 얻어오기
        FragmentManager fm = getSupportFragmentManager();

 

그리고 FragmentManager객체를 이용해 프레그먼트 객체의 참조값을 얻어낸다.

//FragmentManager객체를 이용해 프레그먼트 객체의 참조값을 얻어낼 수 있다.
        Fragment frag1 = fm.findFragmentById(R.id.fragment1);

여기서 reset()메서드를 호출을 한다.

하지만 하려는데 오류가 발생한다. 이는 참조값을 얻기는 했지만 얻어온 값이 부모타입 Fragment 으로 리턴되기 때문에  fm.findFragmentById로 얻어온 참조값을  MyFragment로 casting을 해주어야 한다.

 

'수업내용' 카테고리의 다른 글

20230727 Android  (0) 2023.07.28
20230727 Kotlin Function  (0) 2023.07.27
20230726 Kotlin  (0) 2023.07.26
20230725 Android 다른화면으로 넘어가기  (0) 2023.07.25
20230725 Android  (0) 2023.07.25

댓글