Android ExpandableListView 예제 자습서
Android ExpandableListView 예제 자습서에 오신 것을 환영합니다. 이 튜토리얼에서는 범주별로 목록 데이터를 그룹화하는 데 사용되는 ExpandableListView를 구현합니다. Android ListView의 일종의 메뉴 및 하위 메뉴입니다.
Android ExpandableListView
Android ExpandableListView는 세로로 스크롤되는 2단계 목록에 항목을 표시하는 뷰입니다. 보기를 터치하여 쉽게 확장 및 축소할 수 있는 그룹인 두 수준과 해당 하위 항목을 허용한다는 점에서 ListView와 다릅니다. android의 ExpandableListViewAdapter는 이 보기와 연결된 항목에 데이터를 로드합니다. 다음은 이 클래스에서 사용되는 몇 가지 중요한 메서드입니다.
- setChildIndicator(Drawable) : 현재 상태를 나타내는 각 항목 옆에 표시기를 표시하는 데 사용됩니다. 하위가 그룹의 마지막 하위인 경우
state_last
상태가 설정됩니다 - setGroupIndicator(Drawable) : 확장 또는 축소와 같은 상태를 나타내는 그룹 옆에 표시기가 그려집니다. 그룹이 비어 있으면
state_empty
상태가 설정됩니다. 그룹이 확장되면state_expanded
상태가 설정됩니다 - getGroupView() : 목록 그룹 헤더에 대한 뷰를 반환합니다.
- getChildView() : 목록 하위 항목에 대한 뷰를 반환합니다.
이 클래스에 의해 구현되는 주목할만한 인터페이스는 다음과 같습니다.
- ExpandableListView.OnChildClickListener : 확장된 목록의 자식이 클릭될 때 호출되는 콜백 메서드를 구현하도록 재정의됩니다.
- ExpandableListView.OnGroupClickListener : 확장 목록의 그룹 헤더를 클릭할 때 호출되는 콜백 메서드를 구현하기 위해 재정의됩니다.
- ExpandableListView.OnGroupCollapseListener : 그룹 축소 시 알림을 위해 사용
- ExpandableListView.OnGroupExpandListener : 그룹 확장 시 알림을 위해 사용
Android ExpandableListView 프로젝트 구조
- ExpandableListView로 레이아웃을 보여주는 MainActivity
- 목록의 임의 데이터를 나타내고 HashMap을 사용하여 하위 항목 데이터를 각 그룹 헤더에 매핑하는 ExpandableListDataPump
- MainActivity에 ExpandableListDataPump 클래스의 데이터를 제공하는 CustomExpandableListAdapter/li>
Android ExpandableListView 코드
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>
android:indicatorLeft는 항목 표시기의 왼쪽 경계입니다. 참고: 부모의 크기가 엄격하게 지정되지 않는 한 XML에서 ExpandableListView
의 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;
}
});
}
}
Android ExpandableListView 예제 프로젝트 다운로드