Android ExpandableListView 예제 튜토리얼에 오신 것을 환영합니다. 이 튜토리얼에서는 카테고리별로 목록 데이터를 그룹화하는 ExpandableListView를 구현합니다. 이는 Android ListView에서 메뉴와 하위 메뉴와 같은 역할을 합니다.
Android ExpandableListView
Android ExpandableListView는 세로로 스크롤되는 두 단계 목록을 보여주는 뷰입니다. ListView와는 달리 이 뷰에서는 쉽게 확장 및 축소할 수 있는 두 단계인 그룹과 해당하는 자식 아이템이 있습니다. 안드로이드에서의 ExpandableListViewAdapter는 이 뷰와 연결된 아이템에 데이터를 로드합니다. 이 클래스에서 사용되는 몇 가지 중요한 메소드는 다음과 같습니다:
- setChildIndicator(Drawable): 현재 상태를 나타내는 각 항목 옆에 인디케이터를 표시하는 데 사용됩니다. 자식이 그룹의 마지막 자식인 경우, 상태
state_last
가 설정됩니다. - setGroupIndicator(Drawable): 그룹 옆에 상태(확장 또는 축소)를 나타내는 인디케이터가 그려집니다. 그룹이 비어 있으면 상태
state_empty
가 설정됩니다. 그룹이 확장되면 상태state_expanded
가 설정됩니다. - getGroupView(): 목록 그룹 헤더에 대한 뷰를 반환합니다.
- getChildView() : 리스트 자식 항목에 대한 뷰를 반환합니다.
이 클래스에서 구현된 주목할만한 인터페이스는 다음과 같습니다 :
- ExpandableListView.OnChildClickListener : 이것은 확장된 목록에서 자식을 클릭할 때 호출되는 콜백 메서드를 구현하기 위해 재정의됩니다.
- ExpandableListView.OnGroupClickListener : 이것은 확장된 목록에서 그룹 헤더를 클릭할 때 호출되는 콜백 메서드를 구현하기 위해 재정의됩니다.
- ExpandableListView.OnGroupCollapseListener : 그룹이 축소될 때 알림을 받기 위해 사용됩니다.
- ExpandableListView.OnGroupExpandListener : 그룹이 확장될 때 알림을 받기 위해 사용됩니다.
Android ExpandableListView 프로젝트 구조
- A MainActivity that shows the layout with the ExpandableListView
- ExpandableListDataPump은 리스트의 무작위 데이터를 나타내고 HashMap을 사용하여 해당 그룹 헤더에 자식 항목 데이터를 매핑합니다.
- A CustomExpandableListAdapter which provides the MainActivity with the data from the ExpandableListDataPump class/li>
Android ExpandableListView Code
activity_main.xml 레이아웃은 다음과 같이 RelativeLayout 안에 ExpandableListView로 구성되어 있습니다 : activity_main.xml
<RelativeLayout xmlns:android="https://schemas.android.com/apk/res/android"
xmlns:tools="https://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
android:paddingBottom="@dimen/activity_vertical_margin"
tools:context=".MainActivity">
<ExpandableListView
android:id="@+id/expandableListView"
android:layout_height="match_parent"
android:layout_width="match_parent"
android:indicatorLeft="?android:attr/expandableListPreferredItemIndicatorLeft"
android:divider="@android:color/darker_gray"
android:dividerHeight="0.5dp" />
</RelativeLayout>
The android:indicatorLeft는 항목 표시기의 왼쪽 경계입니다. 참고 : 부모의 크기가 엄격하게 지정된 경우에만 XML의 android:layout_height 속성에 대해 wrap_content 값을 사용할 수 없습니다. 각 개별 목록의 그룹 헤더 레이아웃은 다음과 같습니다 : list_group.xml
<?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:paddingLeft="?android:attr/expandableListPreferredItemPaddingLeft"
android:textColor="@android:color/black"
android:paddingTop="10dp"
android:paddingBottom="10dp" />
</LinearLayout>
자식 항목의 레이아웃 행은 다음과 같습니다 : list_item.xml
<?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="wrap_content">
<TextView
android:id="@+id/expandedListItem"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:paddingLeft="?android:attr/expandableListPreferredChildPaddingLeft"
android:paddingTop="10dp"
android:paddingBottom="10dp" />
</LinearLayout>
ExpandableListDataPump
클래스는 다음과 같이 정의됩니다:
package com.journaldev.expandablelistview;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
public class ExpandableListDataPump {
public static HashMap<String, List<String>> getData() {
HashMap<String, List<String>> expandableListDetail = new HashMap<String, List<String>>();
List<String> cricket = new ArrayList<String>();
cricket.add("India");
cricket.add("Pakistan");
cricket.add("Australia");
cricket.add("England");
cricket.add("South Africa");
List<String> football = new ArrayList<String>();
football.add("Brazil");
football.add("Spain");
football.add("Germany");
football.add("Netherlands");
football.add("Italy");
List<String> basketball = new ArrayList<String>();
basketball.add("United States");
basketball.add("Spain");
basketball.add("Argentina");
basketball.add("France");
basketball.add("Russia");
expandableListDetail.put("CRICKET TEAMS", cricket);
expandableListDetail.put("FOOTBALL TEAMS", football);
expandableListDetail.put("BASKETBALL TEAMS", basketball);
return expandableListDetail;
}
}
위의 코드에서 expandableListDetail
객체는 문자열 그룹 헤더를 해당 자식과 매핑하기 위해 문자열의 ArrayList를 사용합니다. CustomExpandableListAdapter.java
package com.journaldev.expandablelistview;
import java.util.HashMap;
import java.util.List;
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;
public class CustomExpandableListAdapter extends BaseExpandableListAdapter {
private Context context;
private List<String> expandableListTitle;
private HashMap<String, List<String>> expandableListDetail;
public 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 this.expandableListDetail.get(this.expandableListTitle.get(listPosition))
.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 = layoutInflater.inflate(R.layout.list_item, null);
}
TextView expandedListTextView = (TextView) convertView
.findViewById(R.id.expandedListItem);
expandedListTextView.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 = layoutInflater.inflate(R.layout.list_group, null);
}
TextView listTitleTextView = (TextView) 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;
}
}
이 클래스는 BaseExpandableListAdapter를 확장하며, 기본 클래스의 메서드를 재정의하여 ExpandableListView의 뷰를 제공합니다. getView()는 주어진 인덱스의 항목 뷰에 데이터를 채웁니다. MainActivity.java
package com.journaldev.expandablelistview;
import android.support.v7.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 = (ExpandableListView) findViewById(R.id.expandableListView);
expandableListDetail = ExpandableListDataPump.getData();
expandableListTitle = new ArrayList<String>(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;
}
});
}
}
위의 코드에서는 이전에 논의된 모든 인터페이스를 구현했습니다. 간편함을 위해 모든 클릭에 대해 항목 이름이나 그룹 상태를 나타내는 Toast만 표시합니다. 그러나 이것들은 쉽게 수정되어 다른 작업을 수행하도록 변경할 수 있습니다. 아래는 Android 확장 가능한 목록 뷰가 작동하는 앱입니다. 참고: ExpandableListViews는 기본적으로 스크롤 가능합니다. Android ExpandableListView 튜토리얼은 여기까지입니다. 최종 Android ExpandableListView 프로젝트는 아래 링크에서 다운로드할 수 있습니다.
Source:
https://www.digitalocean.com/community/tutorials/android-expandablelistview-example-tutorial