Android

리스트 선택 : DialogFragment + ViewPager + 리스너연결

그란. 2019. 4. 19. 15:53

 

구조

MainActivity 아이템 추가 버튼

 

DiaglogFragment [ TabLayout + ViewPager ] 

  • Fragment1 [ RecyclerView ]  (1 Page)
  • Fragment2 [ RecyclerView ]  (2 Page)
  • Fragment3 [ RecyclerView ]  (3 Page)

( Fragment1,2,3 은 중복이라 재활용 예정 )

 

 

MainActivity 

   FragmentManager fm = getSupportFragmentManager();
   ArrayList<ArrayList<ProductModel.ODS0>> items = new ArrayList<>();
   items.add(productList1);
   items.add(productList2);
   items.add(productList3);
   productFragment = ProductFragment.newInstance(items);
   productFragment.show(fm, "productFragment");

 

  1. newInstance(items)로 리스트를 넘겨줌 (각각 1,2,3 Page에서 보여질 리스트들)
  2. DialogFragment 상속한 ProductFragment 화면을 띄움

 

 

ProductFragment extends DialogFragment

    public static ProductFragment newInstance(ArrayList<ArrayList<ProductModel.ODS0>> items) {
        ProductFragment fragment = new ProductFragment();
        Bundle args = new Bundle();
        args.putSerializable(KEY_DATA,items);
        fragment.setArguments(args);
        return fragment;
    }

 

  1. Bundle에 리스트를 넣어 Fragment에 이식
  2. 리스트가 하나였다면 putParcelableArrayList로 하지만 이 경우에는 리스트의 리스트이므로 어쩔수 없이 
    putSerializable을 사용함

cf) Model 클래스를 Serializable보다 Parcelable 이 좋다고 함 ( 이유는 모르겠지만 Parcelable 쓰는게 안정적이라고 함 )

 

@Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        return inflater.inflate(R.layout.fragment_product_list, container, false);

    }

    @Override
    public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);

        tabLayout = view.findViewById(R.id.product_pick_tablayout);
        viewPager = view.findViewById(R.id.product_pick_viewpager);

        tabLayout.addTab(tabLayout.newTab().setText(R.string.product_type_1));
        tabLayout.addTab(tabLayout.newTab().setText(R.string.product_type_2));
        tabLayout.addTab(tabLayout.newTab().setText(R.string.product_type_3));

        tabLayout.setTabGravity(TabLayout.GRAVITY_FILL);
        tabLayout.setupWithViewPager(viewPager);
        tabLayout.addOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
            @Override
            public void onTabSelected(TabLayout.Tab tab) {
                viewPager.setCurrentItem(tab.getPosition());
            }

            @Override
            public void onTabUnselected(TabLayout.Tab tab) {

            }

            @Override
            public void onTabReselected(TabLayout.Tab tab) {

            }
        });

        ProductTabPagerAdapter pagerAdapter = new ProductTabPagerAdapter(
        	getChildFragmentManager(),
                getContext(),
                (List<ArrayList<ProductModel.ODS0>>) getArguments().getSerializable(KEY_DATA)
        );
        viewPager.setAdapter(pagerAdapter);
        viewPager.setOffscreenPageLimit(2);
        viewPager.addOnPageChangeListener(new TabLayout.TabLayoutOnPageChangeListener(tabLayout));

        btn_product_pick_save = view.findViewById(R.id.btn_product_pick_save);
        btn_product_pick_save.setOnClickListener(v -> dismiss());

        viewPager.setCurrentItem(0);

    }
  • * Fragment 생성 주기 -> onCreate -> onViewCreated
  • onViewCreated 함수에서 위젯연결 및 이벤트 처리하는게 더 깔끔한듯 
  • FragmentStatePagerAdapter ( ProductTabPagerAdapter )에 리스트를 PagerAdapter에 넘길때 getArguments().getSerializable(KEY_DATA) 하면 되지만

    이 경우에는 리스트의 리스트를 넘겨야해서 (List<ArrayList<ProductModel.ODS0>>) 캐스팅

 

 

ProductTabPagerAdapter 

public class ProductTabPagerAdapter extends FragmentStatePagerAdapter {

    private Context context;
    private List<ArrayList<ProductModel.ODS0>> items;

    public ProductTabPagerAdapter(FragmentManager childFragmentManager,  Context context, List<ArrayList<ProductModel.ODS0>> items) {
        super(childFragmentManager);
        this.context = context;
        this.items = items;
    }

    @Override
    public int getItemPosition(@NonNull Object object) {
        return POSITION_NONE;
    }

    @Override
    public Fragment getItem(int i) {
        return ProductFilterFragment.newInstance(items.get(i));
    }

    @Override
    public int getCount() {
        return items.size();
    }

    @Nullable
    @Override
    public CharSequence getPageTitle(int position) {
        switch (position) {
            case 0:
                return context.getString(R.string.product_type_1);
            case 1:
                return context.getString(R.string.product_type_2);
            case 2:
                return context.getString(R.string.product_type_3);
            default:
                return null;
        }
    }
}

 

 

ProductFilterFragment ( 각 RecyclerView 를 가지고 있는 Fragmet )

  public static ProductFilterFragment newInstance(ArrayList<ProductModel.ODS0> list) {
        Bundle args = new Bundle();
        args.putParcelableArrayList(KEY_DATA, list);
        ProductFilterFragment fragment = new ProductFilterFragment();
        fragment.setArguments(args);
        return fragment;
    }

 

@Override
    public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        RecyclerView recyclerView = view.findViewById(R.id.product_pick_recycler);
        recyclerView.setLayoutManager(new LinearLayoutManager(getContext()));
        adapter = new MyProductRecyclerViewAdapter(getArguments().getParcelableArrayList(KEY_DATA), mListener);
        recyclerView.setAdapter(adapter);
    }

    @Override
    public void onAttach(Context context) {
        super.onAttach(context);
        if (context instanceof OnFilterFragmentInteractionListener) {
            mListener = (OnFilterFragmentInteractionListener) context;
        } else {
            throw new RuntimeException(context.toString()
                    + " must implement OnFragmentInteractionListener");
        }
    }


    @Override
    public void onDetach() {
        super.onDetach();
        mListener = null;
    }

    public interface OnFilterFragmentInteractionListener {
        void onFilterFragmentInteractionListener(ProductModel.ODS0 productModel);
    }

리스너 연결과 어댑터에 리스트 연결

 

 

MyProductRecyclerViewAdapter (리사이클러뷰 어댑터)

public class MyProductRecyclerViewAdapter extends RecyclerView.Adapter<MyProductRecyclerViewAdapter.ViewHolder> {

    private final OnFilterFragmentInteractionListener mListener;
    private List<ProductModel.ODS0> productModels;

    public MyProductRecyclerViewAdapter(List<ProductModel.ODS0> productModels, OnFilterFragmentInteractionListener listener) {
        this.productModels = productModels;
        mListener = listener;
    }

    @Override
    public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        View view = LayoutInflater.from(parent.getContext())
                .inflate(R.layout.fragment_product_pick, parent, false);
        return new ViewHolder(view);
    }

    @Override
    public void onBindViewHolder(final ViewHolder holder, int position) {

        holder.mItem = productModels.get(position);
        holder.g_code.setText(productModels.get(position).getGCODE());
        holder.g_name.setText(productModels.get(position).getGNAME());
        holder.g_type.setText(productModels.get(position).getItem_type_nm());
        holder.stk_cnt.setText(productModels.get(position).getSTKCNT().toString());

        if (productModels.get(position).isSelected()) {
            holder.view_foreground.setBackgroundColor(Color.LTGRAY);
        } else {
            holder.view_foreground.setBackgroundColor(Color.WHITE);
        }
    }

    @Override
    public int getItemCount() {
        return productModels.size();
    }

    public class ViewHolder extends RecyclerView.ViewHolder {
        public final LinearLayout view_foreground;
        public final View mView;
        public final TextView g_code;
        public final TextView g_name;
        public final TextView g_type;
        public final TextView stk_cnt;
        public ProductModel.ODS0 mItem;

        public ViewHolder(View view) {
            super(view);
            mView = view;
            view_foreground = view.findViewById(R.id.view_foreground);
            g_code = view.findViewById(R.id.g_code);
            g_name = view.findViewById(R.id.g_name);
            g_type = view.findViewById(R.id.g_type);
            stk_cnt = view.findViewById(R.id.stk_cnt);
           
           view_foreground.setOnClickListener(view1 -> {
                if (null != mListener) {
                    productModels.get(getAdapterPosition()).setSelected(true);
                    notifyItemChanged(getAdapterPosition());
                    mListener.onFilterFragmentInteractionListener(mItem);
                }
            });
           
        }
    }
}

 

 

긴 여정 끝에 MainActivity에서 리스너를 받음

@Override
    public void onFilterFragmentInteractionListener(ProductModel.ODS0 item) {
      
         리스트 선택시 작업
      
    }