Android Fragment

안드로이드 / / 2021. 11. 14. 23:00
반응형

Fragment 사용법

  • 특정 영역을 해당 프레그먼트로 교체(replace)
    • 교체시에는 기존 프레그먼트들 모두 삭제됨
  • 프레그먼트 추가(add)
  • 프레그먼트 삭제(remove)

 

MainActivity.java

package com.srctree.fragment;

import androidx.appcompat.app.AppCompatActivity;
import androidx.fragment.app.Fragment;

import android.graphics.Color;
import android.os.Bundle;
import android.os.Handler;
import android.view.View;
import android.widget.Button;
import android.widget.FrameLayout;
import android.widget.TextView;

import java.util.Random;

public class MainActivity extends AppCompatActivity implements View.OnClickListener {

    Button btn_red;
    Button btn_blue;
    Button btn_green;
    TextView tv_stack_count;
    Button btn_add;
    Button btn_remove;
    FrameLayout frame_container;

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

        btn_red = findViewById(R.id.btn_red);
        btn_blue = findViewById(R.id.btn_blue);
        btn_green = findViewById(R.id.btn_green);
        tv_stack_count = findViewById(R.id.tv_stack_count);
        btn_add = findViewById(R.id.btn_add);
        btn_remove = findViewById(R.id.btn_remove);
        frame_container = findViewById(R.id.frame_container);

        btn_red.setOnClickListener(this);
        btn_blue.setOnClickListener(this);
        btn_green.setOnClickListener(this);
        btn_add.setOnClickListener(this);
        btn_remove.setOnClickListener(this);

        setFragCount();
    }

    @Override
    public void onClick(View view) {
        if(view == btn_red) {//빨강 프레그먼트로 교체(기존 프레그먼트 모두 삭제됨)
            getSupportFragmentManager().beginTransaction().replace(R.id.frame_container, ColorFragment.newInstance(Color.RED)).commit();
            setFragCount();
        } else if(view == btn_blue) {//파랑 프레그먼트로 교체(기존 프레그먼트 모두 삭제됨)
            getSupportFragmentManager().beginTransaction().replace(R.id.frame_container, ColorFragment.newInstance(Color.BLUE)).commit();
            setFragCount();
        } else if(view == btn_green) {//녹색 프레그먼트로 교체(기존 프레그먼트 모두 삭제됨)
            getSupportFragmentManager().beginTransaction().replace(R.id.frame_container, ColorFragment.newInstance(Color.GREEN)).commit();
            setFragCount();
        } else if(view == btn_add) {//프레그먼트 추가
            Random random = new Random();
            int color = Color.rgb(random.nextInt(255), random.nextInt(255), random.nextInt(255));
            getSupportFragmentManager().beginTransaction().add(R.id.frame_container, ColorFragment.newInstance(color)).commit();
            setFragCount();
        } else if(view == btn_remove) {//최상단 프레그먼트 삭제
            if(getSupportFragmentManager().getFragments().size() > 0) {
                Fragment topFlag = getSupportFragmentManager().getFragments().get(getSupportFragmentManager().getFragments().size() - 1);
                getSupportFragmentManager().beginTransaction().remove(topFlag).commit();
                setFragCount();
            }
        }
    }

    //현재의 프레그먼트 개수
    void setFragCount() {
        new Handler().postDelayed(new Runnable() {
            @Override
            public void run() {
                tv_stack_count.setText("Fragment : " + getSupportFragmentManager().getFragments().size() + "개");
            }
        }, 500);
    }
}

ColorFragment.java

package com.srctree.fragment;

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;

public class ColorFragment extends Fragment {
    int color;
    TextView tv_num;

    public static ColorFragment newInstance(int color) {
        ColorFragment fragment = new ColorFragment();
        fragment.color = color;
        return fragment;
    }

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_color, container, false);
        tv_num = view.findViewById(R.id.tv_num);
        tv_num.setBackgroundColor(color);
        return view;
    }
}

activity.main

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

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="50dp"
        android:orientation="horizontal">
        <TextView
            android:layout_width="120dp"
            android:layout_height="wrap_content"
            android:text="Replace"/>
        <Button
            android:id="@+id/btn_red"
            android:layout_width="wrap_content"
            android:layout_height="match_parent"
            android:text="Red"/>
        <Button
            android:id="@+id/btn_blue"
            android:layout_width="wrap_content"
            android:layout_height="match_parent"
            android:layout_marginLeft="5dp"
            android:text="Blue"/>
        <Button
            android:id="@+id/btn_green"
            android:layout_width="wrap_content"
            android:layout_height="match_parent"
            android:layout_marginLeft="5dp"
            android:text="Green"/>
    </LinearLayout>
    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="50dp"
        android:orientation="horizontal">
        <TextView
            android:id="@+id/tv_stack_count"
            android:layout_width="120dp"
            android:layout_height="wrap_content"
            android:text="Fragment : -개"/>
        <Button
            android:id="@+id/btn_add"
            android:layout_width="wrap_content"
            android:layout_height="match_parent"
            android:text="Add"/>
        <Button
            android:id="@+id/btn_remove"
            android:layout_width="wrap_content"
            android:layout_height="match_parent"
            android:layout_marginLeft="5dp"
            android:text="Remove"/>

    </LinearLayout>

    <FrameLayout
        android:id="@+id/frame_container"
        android:layout_width="match_parent"
        android:layout_height="0dp"
        android:layout_weight="1"/>

</LinearLayout>

fragment_xml

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

    <TextView
        android:id="@+id/tv_num"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:gravity="center"
        android:textSize="50dp"
        android:text=""/>

</LinearLayout>

 

프로젝트 소스 다운↓

Fragment.zip
0.46MB

반응형

'안드로이드' 카테고리의 다른 글

Android 로딩바 동적 생성, 해제  (0) 2021.11.14
Android Thread, Timer, CountDownTimer  (0) 2021.11.14
Android ViewPager  (0) 2021.11.14
Android Webview(Remote, Local)  (2) 2021.11.14
Android Keyboard Show/Hide 이벤트 수신  (0) 2021.11.14
  • 네이버 블러그 공유하기
  • 네이버 밴드에 공유하기
  • 페이스북 공유하기
  • 카카오스토리 공유하기