마스터Q&A 안드로이드는 안드로이드 개발자들의 질문과 답변을 위한 지식 커뮤니티 사이트입니다. 안드로이드펍에서 운영하고 있습니다. [사용법, 운영진]

Fragment에 ListView 관련

0 추천
public class user_1 extends Fragment {
    private final LinkedHashMap<String, ParentModel> parentItem
            = new LinkedHashMap<String, ParentModel>();
    private ArrayList<ParentModel> itemList = new ArrayList<ParentModel>();
    private HelperAdapter helperAdapter;
    private ExpandableListView expandableListView;

    ViewGroup viewGroup;

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater,
                             @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        viewGroup = (ViewGroup) inflater.inflate(R.layout.user_1, container, false);

expandableListView = viewGroup.findViewById(R.id.expandableListView);
addData();

helperAdapter = new HelperAdapter(getContext(), itemList);
expandableListView.setAdapter(helperAdapter);

expandAllGroup();

expandableListView.setOnChildClickListener(new ExpandableListView.OnChildClickListener() {
    @Override
    public boolean onChildClick(ExpandableListView parent, View view,
                                int parentPosition, int childPosition, long l) {
        ParentModel parentInfo = itemList.get(parentPosition);
        ChildModel childInfo = parentInfo.getItemList().get(childPosition);

if (parentPosition == 0){
    switch (childPosition){
        case  0 : Intent intent = new Intent(getContext(), apple.class);
        startActivity(intent);
        break;

        case 1: Intent intent1 = new Intent(getContext(), banana.class);
        startActivity(intent1);
        break;
    }
}else if (parentPosition == 1){
    switch (childPosition){
        case  0 : Intent intent = new Intent(getContext(), test_page.class);
            startActivity(intent);
            break;

        case 1: Intent intent1 = new Intent(getContext(), test_page2.class);
            startActivity(intent1);
            break;
    }
}
        return false;
    }
});
 return viewGroup;
}
    private void expandAllGroup() {
int count = helperAdapter.getGroupCount();
for (int parentPosition = 0; parentPosition<count; parentPosition ++){
    expandableListView.expandGroup(parentPosition);
}
    }
    private void addData() {
        addItem("가나 1", "SubItem.1");
        addItem("가나 1", "SubItem.1");
        addItem("가나 2", "SubItem.1");
        addItem("가나 2", "SubItem.1");
    }
private int addItem(String parentItemList, String subItem){
        int parentPosition = 0;
        ParentModel parentInfo = parentItem.get(parentItemList);
        if (parentInfo == null){
            parentInfo = new ParentModel();
            parentInfo.setName(parentItemList);
            parentItem.put(parentItemList, parentInfo);
            itemList.add(parentInfo);
        }
        ArrayList<ChildModel> childItemList = parentInfo.getItemList();
        int listSize = childItemList.size();
        listSize++;
        ChildModel childInfo = new ChildModel();
        childInfo.setName(subItem);
        childItemList.add(childInfo);
        parentInfo.setItemList(childItemList);
        parentPosition = childItemList.indexOf(parentInfo);
        return parentPosition;
}}
childmodel과 ParentModel  입니다. 각각 따로 class를 줬습니다
public class ChildModel {
private String name = "";
public String getName(){
    return name;
}
public void setName(String name){
    this.name = name;
}}
public class ParentModel {
    private String name;
    private ArrayList<ChildModel> itemList = new ArrayList<ChildModel>();
    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public ArrayList<ChildModel> getItemList() {
        return itemList;
    }

    public void setItemList(ArrayList<ChildModel> itemList) {
        this.itemList = itemList;
    }
}


Adapter입니다
public class HelperAdapter extends BaseExpandableListAdapter {
    private final Context context;
    private final ArrayList<ParentModel> childList;
    public HelperAdapter(Context context, ArrayList<ParentModel> childList){
        this.context = context;
        this.childList = childList;
    }
    @Override
    public int getGroupCount() {
        return childList.size();
    }
    @Override
    public int getChildrenCount(int parentPosition) {
        ArrayList<ChildModel> itemList = childList.get(parentPosition).getItemList();
        return itemList.size();
    }
    @Override
    public Object getGroup(int parentPosition) {
        return childList.get(parentPosition);
    }
    @Override
    public Object getChild(int parentPosition, int childPosition) {
                ArrayList<ChildModel> itemList = childList.
                get(parentPosition).getItemList();
        return itemList.get(childPosition);
    }
    @Override
    public long getGroupId(int parentPosition) {
        return parentPosition;
    }
    @Override
    public long getChildId(int parentPosition, int childPosition) {
        return childPosition;
    }
    @Override
    public boolean hasStableIds() {
        return true;
    }
    @Override
    public View getGroupView(int parentPosition, boolean b, View view, ViewGroup viewGroup) {
        ParentModel parentInfo = (ParentModel) getGroup(parentPosition);
        if (view == null){
            LayoutInflater layoutInflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
            view = layoutInflater.inflate(R.layout.parent_items, viewGroup,false);
        }
        TextView textView = view.findViewById(R.id.parent_txt);
        textView.setText(parentInfo.getName().trim());
        return view;
    }
    @Override
    public View getChildView(int parentPosition, int childPosition, boolean b, View view, ViewGroup viewGroup) {
        ChildModel childInfo = (ChildModel) getChild(parentPosition, childPosition);
        if (view == null){
            LayoutInflater layoutInflater = (LayoutInflater) context.
                    getSystemService(Context.LAYOUT_INFLATER_SERVICE);
            view = layoutInflater.inflate(R.layout.child_items,viewGroup, false);
        }
        TextView childItem = view.findViewById(R.id.child_txt);
        childItem.setText(childInfo.getName().trim());
        return view;
    }
    @Override
    public boolean isChildSelectable(int parentPosition, int childPosition) {
        return true;
    }
}

Bottomnavigation에서 1, 2 번 탭 중에 1번에 ExpandableListView을 준 상태입니다

Listview에서는 chilposition을 터치하는 거 까지 오류없이 잘 되는 상태입니다

근데 bottom 탭에서 2번을 터치하고 다시 1번으로 들어가면 ListView child목록이 그 개수 만큼 늘어나는 현상이 생깁니다.

예로 들자면

가나다

--- a

--- b

--- c

이렇게 차일드 뷰가 세개가 있다고 가정하고 bottom 탭 2번을 누르고 다시 1번으로 들어가면

가나다

--- a

--- b

--- c

--- a

--- b

--- c


이렇게 늘어난 상태입니다

근데 그게 탭 1번을 누른 횟수 만큼 늘어납니다

혹시 이 경우 bottom의 문제인가요? 아니면 ListView의 문제인가요?

다른 bottom 탭은 정상돌아갑니다(아직 나머지 탭 화면을 다 채워넣은건 아니지만 아직까지는 정상작동 하는걸로 보여집니다)

근데 listview를 넣은 탭만 이런 오류가 생겨서 질문드립니다

뽕짝 (390 포인트) 님이 2022년 1월 12일 질문
뽕짝님이 2022년 1월 13일 수정
관련 코드를 올려보세요. 님이 작성하신 코드에 대한 질문이기 때문에, 위의 질문의 내용 만으로는 어디가 문제인지 알 수가 없어요.
주어진 정보만으로 추측해 볼 때, 백스택과 라이프사이클에 관련된 문제일 것으로 보입니다. 화면이 이동하면서 onStart 등에 있는 데이터를 로딩하는 로직이 여러번 실행된 듯해 보이늗데, 추측일 뿐 코드를 보기 전에는 정확한 원인은 알 수가 없을 것 같아요
수정하여 코드 올렸습니다.
Fragment에서의 실수 일까요??
질문을 보면 BottomNavigationView의  NavigationItem 을 두번 클릭하고 나서 이동하면 데이터 중복이 생긴다고 하셨는데, 제가 이해하기로는 이게 이 부분에 문제가 있을 거라고 보시는 것 같거든요. 그렇다면, 프레그먼트와 BottomNavigation에 대한 코드도 있어야 할 것 같은데요. 그리고 코드를 올리시기로 하셨으면 실행가능한 형태를 공유해주시는게 좋아요. 여기에 올리시기 힘드시면 Github같은데 공유를 해주시면 봐드릴 수는 있는데, 바로 실행이 안되는 부분적인 코드만 올려주시면, 간단한 경우는 바로 잡을 수 있지만, 님과 같이 네비게이션이나 라이프 사이클과 관련된 것으로 보이는 경우는 전체를 실행해야만 문제를 잡아낼 가능성이 큽니다.
현재 올리신 코드로는 일단 실행하는데 이것 저것 고쳐야할 것 같고, 코드만 봐서는 문제가 있을 것 같지는 않아 보입니다.

답변 달기

· 글에 소스 코드 보기 좋게 넣는 법
· 질문에 대해 추가적인 질문이나 의견이 있으면 답변이 아니라 댓글로 달아주시기 바랍니다.
표시할 이름 (옵션):
개인정보: 당신의 이메일은 이 알림을 보내는데만 사용됩니다.
스팸 차단 검사:
스팸 검사를 다시 받지 않으려면 로그인하거나 혹은 가입 하세요.
...