Computer >> 컴퓨터 >  >> 프로그래밍 >> Android

Android 앱에서 다단계 ListView(ExpandableListView) 구현하는 방법 – 단계별 가이드

개요

이 튜토리얼에서는 안드로이드 앱에서 ExpandableListView를 활용해 다단계(그룹–하위 항목) 구조의 리스트뷰를 만드는 방법을 단계별로 살펴봅니다. ExpandableListView는 항목을 카테고리별로 그룹화하고, 그룹을 탭하면 하위 항목이 펼쳐지거나 접히는 UI를 제공하기 때문에 설정 메뉴, FAQ 목록, 분류된 콘텐츠 목록 등 다양한 화면에서 유용하게 활용할 수 있습니다.

1단계 – 새 프로젝트 생성

Android Studio에서 File → New Project로 이동한 뒤, 프로젝트 생성에 필요한 모든 정보를 입력하여 새 프로젝트를 만듭니다.

2단계 – activity_main.xml 레이아웃 작성

res/layout/activity_main.xml 파일에 아래 코드를 추가합니다. 화면 전체를 채우는 ExpandableListView 하나를 배치하고, 항목 사이의 구분선 색상과 두께를 지정합니다.

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="https://schemas.android.com/apk/res/android"
    xmlns:tools="https://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:padding="4dp"
    android:layout_height="match_parent"
    tools:context=".MainActivity">
    <ExpandableListView
        android:id="@+id/expendableList"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:divider="@android:color/background_light"
        android:dividerHeight="0.5dp"/>
</RelativeLayout>

3단계 – MainActivity.java 작성

src/MainActivity.java에 아래 코드를 추가합니다. 여기서는 데이터를 어댑터에 연결하고, 그룹이 펼쳐지거나 접힐 때, 그리고 하위 항목을 클릭했을 때 Toast 메시지를 표시하도록 리스너를 설정합니다.

import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.ExpandableListAdapter;
import android.widget.ExpandableListView;
import android.widget.Toast;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
public class MainActivity extends AppCompatActivity {
    ExpandableListView expandableListView;
    ExpandableListAdapter expandableListAdapter;
    List<String>expandableListTitle;
    HashMap<String, List<String>> expandableListDetail;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        expandableListView = findViewById(R.id.expendableList);
        expandableListDetail = ExpandableListData.getData();
        expandableListTitle = new ArrayList<>(expandableListDetail.keySet());
        expandableListAdapter = new CustomExpandableListAdapter(this, expandableListTitle, expandableListDetail);
        expandableListView.setAdapter(expandableListAdapter);
        expandableListView.setOnGroupExpandListener(new ExpandableListView.OnGroupExpandListener() {
            @Override
            public void onGroupExpand(int groupPosition) {
            Toast.makeText(getApplicationContext(), expandableListTitle.get(groupPosition)
                + " List Expanded.", Toast.LENGTH_SHORT).show();
        }
    });
    expandableListView.setOnGroupCollapseListener(new ExpandableListView.OnGroupCollapseListener() {
        @Override
        public void onGroupCollapse(int groupPosition) {
            Toast.makeText(getApplicationContext(), expandableListTitle.get(groupPosition) + " List Collapsed.",
                Toast.LENGTH_SHORT).show();
        }
    });
    expandableListView.setOnChildClickListener(new ExpandableListView.OnChildClickListener() {
        @Override
        public boolean onChildClick(ExpandableListView parent, View v, int groupPosition, int childPosition, long id) {
                Toast.makeText( getApplicationContext(), expandableListTitle.get(groupPosition) + "
                   -> " + expandableListDetail.get( expandableListTitle.get(groupPosition)).get( childPosition), Toast.LENGTH_SHORT ).show();
                return false;
           }
        });
    }
}

4단계 – 데이터 클래스(ExpandableListData.java) 생성

새 자바 클래스 ExpandableListData.java를 만들고 아래 코드를 입력합니다. 이 클래스는 그룹 이름을 키로, 해당 그룹에 속한 선수 명단을 값으로 갖는 HashMap 형태의 샘플 데이터를 반환합니다.

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
class ExpandableListData {
    static HashMap<String, List<String>> getData() {
        HashMap<String, List<String>> expandableListDetail = new HashMap<>();
        List<String> myFavCricketPlayers = new ArrayList<>();
        myFavCricketPlayers.add("MS.Dhoni");
        myFavCricketPlayers.add("Sehwag");
        myFavCricketPlayers.add("Shane Watson");
        myFavCricketPlayers.add("Ricky Ponting");
        myFavCricketPlayers.add("Shahid Afridi");
        List<String> myFavFootballPlayers = new ArrayList<String>();
        myFavFootballPlayers.add("Cristiano Ronaldo");
        myFavFootballPlayers.add("Lionel Messi");
        myFavFootballPlayers.add("Gareth Bale");
        myFavFootballPlayers.add("Neymar JR");
        myFavFootballPlayers.add("David de Gea");
        List<String> myFavTennisPlayers = new ArrayList<String>();
        myFavTennisPlayers.add("Roger Federer");
        myFavTennisPlayers.add("Rafael Nadal");
        myFavTennisPlayers.add("Andy Murray");
        myFavTennisPlayers.add("Novak Jokovic");
        myFavTennisPlayers.add("Sania Mirza");
        expandableListDetail.put("CRICKET PLAYERS", myFavCricketPlayers);
        expandableListDetail.put("FOOTBALL PLAYERS", myFavFootballPlayers);
        expandableListDetail.put("TENNIS PLAYERS", myFavTennisPlayers);
        return expandableListDetail;
    }
}

5단계 – 커스텀 어댑터(CustomExpandableListAdapter.java) 생성

새 자바 클래스 CustomExpandableListAdapter.java를 만들고 아래 코드를 추가합니다. BaseExpandableListAdapter를 상속받아 그룹 뷰와 하위 항목 뷰를 직접 구성하며, 그룹 제목은 굵은 글씨로 표시됩니다.

package app.com.sample;
import android.content.Context;
import android.graphics.Typeface;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseExpandableListAdapter;
import android.widget.TextView;
import java.util.HashMap;
import java.util.List;
import java.util.Objects;
class CustomExpandableListAdapter extends BaseExpandableListAdapter {
    private Context context;
    private List<String> expandableListTitle;
    private HashMap<String, List<String>> expandableListDetail;
    CustomExpandableListAdapter(Context context, List<String> expandableListTitle, HashMap<String, List<String>> expandableListDetail) {
        this.context = context;
        this.expandableListTitle = expandableListTitle;
        this.expandableListDetail = expandableListDetail;
    }
    @Override
    public Object getChild(int listPosition, int expandedListPosition) {
        return
        Objects.requireNonNull(this.expandableListDetail.get(this.expandableListTitle.get(list Position))).get(expandedListPosition);
    }
    @Override
    public long getChildId(int listPosition, int expandedListPosition) {
        return expandedListPosition;
    }
    @Override
    public View getChildView(int listPosition, final int expandedListPosition, boolean isLastChild, View convertView, ViewGroup parent) {
        final String expandedListText = (String) getChild(listPosition, expandedListPosition);
        if (convertView == null) {
            LayoutInflater layoutInflater = (LayoutInflater) this.context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
            convertView = Objects.requireNonNull(layoutInflater).inflate(R.layout.list_row, null);
        }
        TextView textView = convertView.findViewById(R.id.listTitle);
        textView.setText(expandedListText);
        return convertView;
    }
    @Override
    public int getChildrenCount(int listPosition) {
        return
        this.expandableListDetail.get(this.expandableListTitle.get(listPosition)).size();
    }
    @Override
    public Object getGroup(int listPosition) {
        return this.expandableListTitle.get(listPosition);
    }
    @Override
    public int getGroupCount() {
        return this.expandableListTitle.size();
    }
    @Override
    public long getGroupId(int listPosition) {
        return listPosition;
    }
    @Override
    public View getGroupView(int listPosition, boolean isExpanded, View convertView, ViewGroup parent) {
        String listTitle = (String) getGroup(listPosition);
        if (convertView == null) {
            LayoutInflater layoutInflater = (LayoutInflater) this.context. getSystemService(Context.LAYOUT_INFLATER_SERVICE);
            convertView = Objects.requireNonNull(layoutInflater).inflate(R.layout.list_row, null);
        }
        TextView listTitleTextView = convertView.findViewById(R.id.listTitle);
        listTitleTextView.setTypeface(null, Typeface.BOLD);
        listTitleTextView.setText(listTitle);
        return convertView;
    }
    @Override
    public boolean hasStableIds() {
        return false;
    }
    @Override
    public boolean isChildSelectable(int listPosition, int expandedListPosition) {
        return true;
    }
}

6단계 – 행 레이아웃(list_row.xml) 생성

새 레이아웃 리소스 파일 list_row.xml을 만들고 아래 코드를 추가합니다. 그룹 제목과 하위 항목 모두 이 단일 TextView 레이아웃을 재사용합니다.

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="https://schemas.android.com/apk/res/android"
    android:orientation="vertical" android:layout_width="match_parent"
    android:layout_height="match_parent">
    <TextView
        android:id="@+id/listTitle"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:padding="10dp"
        android:textColor="@android:color/black" />
</LinearLayout>

7단계 – AndroidManifest.xml 수정

AndroidManifest.xml에 아래 코드를 추가하여 MainActivity를 앱의 시작(Launcher) 액티비티로 등록합니다.

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="https://schemas.android.com/apk/res/android" package="app.com.sample">
    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:roundIcon="@mipmap/ic_launcher_round"
        android:supportsRtl="true"
        android:theme="@style/AppTheme">
            <activity android:name=".MainActivity">
               <intent-filter>
                  <action android:name="android.intent.action.MAIN" />
                  <category android:name="android.intent.category.LAUNCHER" />
              </intent-filter>
        </activity>
    </application>
</manifest>

앱 실행 및 결과 확인

이제 애플리케이션을 실행해 보겠습니다. 실제 안드로이드 기기가 컴퓨터에 연결되어 있다고 가정합니다. Android Studio에서 프로젝트의 액티비티 파일 중 하나를 연 뒤 툴바의 Run 아이콘을 클릭하고, 옵션에서 본인의 모바일 기기를 선택하세요. 그러면 기기 화면에 아래와 같은 기본 화면이 표시됩니다.

Android 앱에서 다단계 ListView(ExpandableListView) 구현하는 방법 – 단계별 가이드

Android 앱에서 다단계 ListView(ExpandableListView) 구현하는 방법 – 단계별 가이드