본문 바로가기
Android Studio

[Android Studio] TabBar Fragment 사용하기

by dong_su 2024. 1. 10.

MainActivity

public class MainActivity extends AppCompatActivity {

    // 아래 아이콘 나오는 영역
    BottomNavigationView bottomNavigationView;

    // 각 프레그먼트를 멤버변수로 만든다.
    Fragment firstFragment;
    Fragment secondFragment;
    Fragment thirdFragment;

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

        SharedPreferences sp = getSharedPreferences(Config.PREFERENCE_NAME, MODE_PRIVATE);
        String token = sp.getString("token", "");

        if (token.isEmpty()){
            Intent intent = new Intent(MainActivity.this, RegisterActivity.class);
            startActivity(intent);
            finish();
            return;
        }

        bottomNavigationView = findViewById(R.id.bottomNavigationView);

        firstFragment = new FirstFragment();
        secondFragment = new SecondFragment();
        thirdFragment = new ThirdFragment();

        bottomNavigationView.setOnItemSelectedListener(new NavigationBarView.OnItemSelectedListener() {
            @Override
            public boolean onNavigationItemSelected(@NonNull MenuItem item) {

                int itemId = item.getItemId();
                Fragment fragment = null;

                if (itemId == R.id.firstFragment){
                    fragment = firstFragment;
                } else if (itemId == R.id.secondFragment) {
                    fragment = secondFragment;
                } else if (itemId == R.id.thirdFragment) {
                    fragment = thirdFragment;
                }
                return loadFragment(fragment);
            }
        });
    }

    boolean loadFragment(Fragment fragment){
        if (fragment != null){
            getSupportFragmentManager().beginTransaction().replace(R.id.fragment, fragment).commit();
            return true;
        } else {
            return false;
        }
    }
}

먼저 메인액티비티에 위 코드처럼 세팅한다.

 

FirstFragment

ProgressBar progressBar;
Button btnAdd;

// 리사이클러뷰 관련 변수
RecyclerView recyclerView;
PostingAdapter adapter;
ArrayList<Posting> postingArrayList = new ArrayList<>();

// 페이징 관련 변수
int offset = 0;
int limit = 7;
int count = 0;

그 후 화면에 보일 프레그먼트 파일로 가서 onCreate() 함수 아래에 전역변수를 작성하고

 

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {
    // Inflate the layout for this fragment
    ViewGroup rootView = (ViewGroup) inflater.inflate(R.layout.fragment_first, container, false);

    progressBar = rootView.findViewById(R.id.progressBar);
    btnAdd = rootView.findViewById(R.id.btnSave);

    recyclerView = rootView.findViewById(R.id.recyclerView);
    recyclerView.setHasFixedSize(true);
    recyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));
    recyclerView.addOnScrollListener(new RecyclerView.OnScrollListener() {
        @Override
        public void onScrolled(@NonNull RecyclerView recyclerView, int dx, int dy) {
            super.onScrolled(recyclerView, dx, dy);

            int lastPosition = ((LinearLayoutManager) recyclerView.getLayoutManager()).findLastVisibleItemPosition();
            int totalCount = recyclerView.getAdapter().getItemCount();

            if (lastPosition+1 == totalCount){
                if (limit == count){
                    addNetworkData();
                }
            }
        }
    });

    btnAdd.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            Intent intent = new Intent(getActivity(), AddActivity.class);
            startActivity(intent);
        }
    });

    return rootView;
}

그동안 메인액티비티의 onCreate() 함수 안에 썼던 코드를 프레그먼트에서는 onCreateView() 안에 작성한다.

그리고 그 외의 함수들은 onCreateView() 밖에서 작성하면 된다.


Fragment 전체 코드

/**
 * A simple {@link Fragment} subclass.
 * Use the {@link FirstFragment#newInstance} factory method to
 * create an instance of this fragment.
 */
public class FirstFragment extends Fragment {

    // TODO: Rename parameter arguments, choose names that match
    // the fragment initialization parameters, e.g. ARG_ITEM_NUMBER
    private static final String ARG_PARAM1 = "param1";
    private static final String ARG_PARAM2 = "param2";

    // TODO: Rename and change types of parameters
    private String mParam1;
    private String mParam2;

    public FirstFragment() {
        // Required empty public constructor
    }

    /**
     * Use this factory method to create a new instance of
     * this fragment using the provided parameters.
     *
     * @param param1 Parameter 1.
     * @param param2 Parameter 2.
     * @return A new instance of fragment firstFragment.
     */
    // TODO: Rename and change types and number of parameters
    public static FirstFragment newInstance(String param1, String param2) {
        FirstFragment fragment = new FirstFragment();
        Bundle args = new Bundle();
        args.putString(ARG_PARAM1, param1);
        args.putString(ARG_PARAM2, param2);
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (getArguments() != null) {
            mParam1 = getArguments().getString(ARG_PARAM1);
            mParam2 = getArguments().getString(ARG_PARAM2);
        }
    }

    ProgressBar progressBar;
    Button btnAdd;

    // 리사이클러뷰 관련 변수
    RecyclerView recyclerView;
    PostingAdapter adapter;
    ArrayList<Posting> postingArrayList = new ArrayList<>();

    // 페이징 관련 변수
    int offset = 0;
    int limit = 7;
    int count = 0;

//    int toggleBtn = 0;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        ViewGroup rootView = (ViewGroup) inflater.inflate(R.layout.fragment_first, container, false);

        progressBar = rootView.findViewById(R.id.progressBar);
        btnAdd = rootView.findViewById(R.id.btnSave);

        recyclerView = rootView.findViewById(R.id.recyclerView);
        recyclerView.setHasFixedSize(true);
        recyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));
        recyclerView.addOnScrollListener(new RecyclerView.OnScrollListener() {
            @Override
            public void onScrolled(@NonNull RecyclerView recyclerView, int dx, int dy) {
                super.onScrolled(recyclerView, dx, dy);

                int lastPosition = ((LinearLayoutManager) recyclerView.getLayoutManager()).findLastVisibleItemPosition();
                int totalCount = recyclerView.getAdapter().getItemCount();

                if (lastPosition+1 == totalCount){
                    if (limit == count){
                        addNetworkData();
                    }
                }
            }
        });

        btnAdd.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(getActivity(), AddActivity.class);
                startActivity(intent);
            }
        });

        return rootView;
    }

    @Override
    public void onResume() {
        getNetworkData();

        super.onResume();
    }

    private void addNetworkData() {
        offset += count;

        progressBar.setVisibility(View.VISIBLE);

        Retrofit retrofit = NetworkClient.getRetrofitClient(getActivity());

        SharedPreferences sp = getActivity().getSharedPreferences(Config.PREFERENCE_NAME, Context.MODE_PRIVATE);
        String token = sp.getString("token", "");

        PostingApi api = retrofit.create(PostingApi.class);

        Call<PostingList> call = api.getMyPostingList("Bearer " + token, offset, limit);

        call.enqueue(new Callback<PostingList>() {
            @Override
            public void onResponse(Call<PostingList> call, Response<PostingList> response) {
                progressBar.setVisibility(View.GONE);

                if (response.isSuccessful()){
                    PostingList postingList = response.body();

                    postingArrayList.addAll(postingList.items);
                    count = postingList.count;

                    adapter.notifyDataSetChanged();

                }
            }

            @Override
            public void onFailure(Call<PostingList> call, Throwable t) {
                progressBar.setVisibility(View.GONE);
                Snackbar.make(btnAdd, "네트워크 통신 실패", Snackbar.LENGTH_SHORT).show();
                return;
            }
        });
    }

    private void getNetworkData() {
        // 변수 초기화
        offset = 0;
        count = 0;

        Retrofit retrofit = NetworkClient.getRetrofitClient(getActivity());

        PostingApi api = retrofit.create(PostingApi.class);

        SharedPreferences sp = getActivity().getSharedPreferences(Config.PREFERENCE_NAME, Context.MODE_PRIVATE);
        String token = sp.getString("token", "");

        Call<PostingList> call = api.getMyPostingList("Bearer " + token, offset, limit);

        call.enqueue(new Callback<PostingList>() {
            @Override
            public void onResponse(Call<PostingList> call, Response<PostingList> response) {
                progressBar.setVisibility(View.GONE);

                if (response.isSuccessful()){
                    PostingList postingList = response.body();

                    postingArrayList.clear();

                    postingArrayList.addAll(postingList.items);
                    count = postingList.count;

                    adapter = new PostingAdapter(getActivity(), postingArrayList);
                    recyclerView.setAdapter(adapter);
                }
            }

            @Override
            public void onFailure(Call<PostingList> call, Throwable t) {
                progressBar.setVisibility(View.GONE);

                Snackbar.make(btnAdd, "네트워크 통신 실패", Snackbar.LENGTH_SHORT).show();
                return;
            }
        });
    }

    // 액션바에 메뉴 아이콘이 나오도록 설정하는 함수
    @Override
    public void onCreateOptionsMenu(@NonNull Menu menu, @NonNull MenuInflater inflater) {
        getActivity().getMenuInflater().inflate(R.menu.main, menu);
    }

    // 액션바의 메뉴 아이콘 클릭했을 때 실행하는 함수
    @Override
    public boolean onOptionsItemSelected(@NonNull MenuItem item) {
        if (item.getItemId() == R.id.menuLogout){
            showAlertDialog();
        }
//        else if (item.getItemId() == R.id.menuFriend) {
//            toggleBtn += 1;
//
//            if (toggleBtn % 2 == 1){
//                if (item.getTitle().equals("친구 포스팅 보기")) {
//                    item.setTitle("내 포스팅 보기");
//                }
//                FriendGetNetworkData();
//            } else {
//                if (item.getTitle().equals("내 포스팅 보기")) {
//                    item.setTitle("친구 포스팅 보기");
//                }
//                getNetworkData();
//            }
//
//        }

        return super.onOptionsItemSelected(item);
    }

    // 팔로우한 회원의 포스팅 보기
//    private void FriendGetNetworkData() {
//        // 변수 초기화
//        offset = 0;
//        count = 0;
//
//        Retrofit retrofit = NetworkClient.getRetrofitClient(MainActivity.this);
//
//        PostingApi api = retrofit.create(PostingApi.class);
//
//        Call<PostingList> call = api.getPostingList("Bearer " + token, offset, limit);
//
//        call.enqueue(new Callback<PostingList>() {
//            @Override
//            public void onResponse(Call<PostingList> call, Response<PostingList> response) {
//                progressBar.setVisibility(View.GONE);
//
//                if (response.isSuccessful()){
//                    PostingList postingList = response.body();
//
//                    postingArrayList.clear();
//
//                    postingArrayList.addAll(postingList.items);
//                    count = postingList.count;
//
//                    adapter = new PostingAdapter(MainActivity.this, postingArrayList);
//                    recyclerView.setAdapter(adapter);
//                }
//            }
//
//            @Override
//            public void onFailure(Call<PostingList> call, Throwable t) {
//                progressBar.setVisibility(View.GONE);
//
//                Snackbar.make(btnAdd, "네트워크 통신 실패", Snackbar.LENGTH_SHORT).show();
//                return;
//            }
//        });
//    }

    // 로그아웃
    private void showAlertDialog() {
        progressBar.setVisibility(View.VISIBLE);

        AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());

        builder.setCancelable(false);

        builder.setTitle("로그아웃 하시겠습니까?");

        builder.setNegativeButton("취소", null);

        builder.setPositiveButton("확인", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                Retrofit retrofit = NetworkClient.getRetrofitClient(getActivity());

                UserApi api = retrofit.create(UserApi.class);

                SharedPreferences sp = getActivity().getSharedPreferences(Config.PREFERENCE_NAME, Context.MODE_PRIVATE);
                String token = sp.getString("token", "");

                Call<Res> call = api.logout("Bearer " + token);

                call.enqueue(new Callback<Res>() {
                    @Override
                    public void onResponse(Call<Res> call, Response<Res> response) {
                        progressBar.setVisibility(View.GONE);

                        if (response.isSuccessful()){
                            SharedPreferences sp = getActivity().getSharedPreferences(Config.PREFERENCE_NAME, Context.MODE_PRIVATE);
                            SharedPreferences.Editor editor = sp.edit();
                            editor.putString("token", "");
                            editor.apply();

                            Snackbar.make(btnAdd, "로그아웃 완료", Snackbar.LENGTH_SHORT).show();

                            Intent intent = new Intent(getActivity(), LoginActivity.class);
                            startActivity(intent);

                            getActivity().finish();
                        }
                    }

                    @Override
                    public void onFailure(Call<Res> call, Throwable t) {
                        progressBar.setVisibility(View.GONE);
                        Snackbar.make(btnAdd, "통신 실패", Snackbar.LENGTH_SHORT).show();
                        return;
                    }
                });
            }
        });

        builder.show();
    }
}