ABOUT ME

-

Today
-
Yesterday
-
Total
-
  • [안드로이드] Fragment 프래그먼트
    Android/공부 2020. 6. 23. 19:21
    프래그먼트는 Activity 내에 생성되는, UI 구성을 여러 개의 모듈 단위로 작성할 수 있도록 해주는 기능이다. 또한 한번 작성된 프래그먼트는 여러 액티비티에서 재사용이 가능하므로 UI 구성에 소요되는 작업량을 많은 부분 감소시킬 수 있다.
    액티비티처럼 하나의 독립된 모듈처럼 실행되기 때문에 액티비티와 연관된 생명주기를 가지고 있으며, 액티비티 실행 중에도 화면에 동적으로 추가되거나 다른 프래그먼트로 교체가 가능하다.  프래그먼트에는 인텐트를 사용할 수 없다.

     

     

    1. xml

    1. activity_main.xml

     

    • 레이아웃에 두개의 프래그먼트(Fragment)를 추가해준다.

     

     

    <fragment
            android:layout_width="match_parent"
            android:layout_height="0dp"
            android:layout_weight="1"
            android:id="@+id/fragment_color_list"
            android:name="com.example.myfragmentex.ColorListFragment"/>
    
    <fragment
            android:id="@+id/fragment_color"
            android:name="com.example.myfragmentex.ColorFragment"
            android:layout_width="match_parent"
            android:layout_height="0dp"
            android:layout_weight="1" />
    • 각 프래그먼트는 ColorFragment와 ColorListFragment에 연결시켜준다.

    • 프래그먼트는 자바 클래스로 생성

     

     

     

     


    2. java

     

     

     

    ▼ ColorFragment와 ColorListFragment의 서브클래스를 사진과 같이 설정한다.

     

     

     

    1. ColorListFragment.class

    package com.example.myfragmentex;
    
    import android.app.Activity;
    import android.content.Context;
    import android.graphics.Color;
    import android.os.Bundle;
    import android.view.View;
    import android.widget.ArrayAdapter;
    import android.widget.ListView;
    
    import androidx.annotation.NonNull;
    import androidx.annotation.Nullable;
    import androidx.fragment.app.ListFragment;
    
    import java.util.Arrays;
    import java.util.List;
    
    public class ColorListFragment extends ListFragment {
    
        private onColorSelectedListener mListener;
    
        public interface onColorSelectedListener {
            void onColorSelectedListener(int color);
        }
    
        // 액티비티와 프래그먼트를 붙여주는 메소드
        @Override
        public void onAttach(@NonNull Context context) {
            super.onAttach(context);
            try {
                mListener = (onColorSelectedListener) context;
            } catch (ClassCastException e) {
                throw new ClassCastException(((Activity) context).getLocalClassName()+
                        "는 OnColorSeletedListener를 구현해야 합니다.");
            }
        }
    
        @Override
        public void onListItemClick(@NonNull ListView l, @NonNull View v, int position, long id) {
            //프래그먼트에 있는 어뎁터를 가져온다.
            ArrayAdapter<String> adapter = (ArrayAdapter<String>) l.getAdapter();
            String colorString = adapter.getItem(position);
            int color = Color.RED;
            switch (colorString) {
                case "Red":
                    color = Color.RED;
                    break;
                case "Blue":
                    color = Color.BLUE;
                    break;
                case "Green":
                    color = Color.GREEN;
                    break;
            }
            if (mListener != null)
                mListener.onColorSelectedListener(color);
        }
    
        // 리스트를 클릭했을때 발생하는 이벤트를 처리하는 메소드
        @Override
        public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
            super.onViewCreated(view, savedInstanceState);
    
            List<String> colorList = Arrays.asList("Red","Green","Blue");
            ArrayAdapter<String> adapter = new ArrayAdapter<String>(getActivity(),
                    android.R.layout.simple_list_item_1, colorList);
            setListAdapter(adapter);
        }
    }
    • ColorListFragment는 ListFragment를 상속받는다.

    • 클래스에는 액티비티와 프래그먼트를 붙일 때 호출하는 함수인 onAttach()를 추가하고,  색상 리스트와 리스트를 클릭했을때 발생하는 이벤트를 처리할 메소드를 정의해준다.

     

     

    2. ColorFragment.class

    package com.example.myfragmentex;
    
    import android.os.Bundle;
    import android.view.LayoutInflater;
    import android.view.View;
    import android.view.ViewGroup;
    
    import androidx.annotation.NonNull;
    import androidx.annotation.Nullable;
    import androidx.fragment.app.Fragment;
    
    public class ColorFragment extends Fragment {
    
        @Nullable
        @Override
        public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
            return new View(getActivity());
        }
    
        // 색상추가
        public void setColor(int color) {
            getView().setBackgroundColor(color);
        }
    }

     

    3. MainActivity.class

    package com.example.myfragmentex;
    
    import androidx.appcompat.app.AppCompatActivity;
    
    import android.graphics.Color;
    import android.os.Bundle;
    
    public class MainActivity extends AppCompatActivity implements ColorListFragment.onColorSelectedListener {
    
        private ColorFragment mColorFragment;
    
        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_main);
    
            mColorFragment = (ColorFragment) getSupportFragmentManager()
                                    .findFragmentById(R.id.fragment_color);
            mColorFragment.setColor(Color.RED);
        }
    
        @Override
        public void onColorSelectedListener(int color) {
            mColorFragment.setColor(color);
        }
    }

     

     


     

    3. 결과화면

     

    댓글

Designed by Tistory.