Android 의 IphoneTreeView 그룹 표시 기의 ExpandableListView 효과
15874 단어 IphoneTreeViewExpandableListView
public class IphoneTreeView extends ExpandableListView implements
OnScrollListener, OnGroupClickListener {
public IphoneTreeView(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
registerListener();
}
public IphoneTreeView(Context context, AttributeSet attrs) {
super(context, attrs);
registerListener();
}
public IphoneTreeView(Context context) {
super(context);
registerListener();
}
/**
* Adapter . .
*/
public interface IphoneTreeHeaderAdapter {
public static final int PINNED_HEADER_GONE = 0;
public static final int PINNED_HEADER_VISIBLE = 1;
public static final int PINNED_HEADER_PUSHED_UP = 2;
/**
* Header
*
* @param groupPosition
* @param childPosition
* @return
* PINNED_HEADER_GONE,PINNED_HEADER_VISIBLE,PINNED_HEADER_PUSHED_UP
*
*/
int getTreeHeaderState(int groupPosition, int childPosition);
/**
* QQHeader, QQHeader
*
* @param header
* @param groupPosition
* @param childPosition
* @param alpha
*/
void configureTreeHeader(View header, int groupPosition,
int childPosition, int alpha);
/**
*
*
* @param groupPosition
* @param status
*/
void onHeadViewClick(int groupPosition, int status);
/**
*
*
* @param groupPosition
* @return
*/
int getHeadViewClickStatus(int groupPosition);
}
private static final int MAX_ALPHA = 255;
private IphoneTreeHeaderAdapter mAdapter;
/**
* View,mHeaderViewVisible true
*/
private View mHeaderView;
/**
*
*/
private boolean mHeaderViewVisible;
private int mHeaderViewWidth;
private int mHeaderViewHeight;
public void setHeaderView(View view) {
mHeaderView = view;
AbsListView.LayoutParams lp = new AbsListView.LayoutParams(
ViewGroup.LayoutParams.MATCH_PARENT,
ViewGroup.LayoutParams.WRAP_CONTENT);
view.setLayoutParams(lp);
if (mHeaderView != null) {
setFadingEdgeLength(0);
}
requestLayout();
}
private void registerListener() {
setOnScrollListener(this);
setOnGroupClickListener(this);
}
/**
* HeaderView
*/
private void headerViewClick() {
long packedPosition = getExpandableListPosition(this
.getFirstVisiblePosition());
int groupPosition = ExpandableListView
.getPackedPositionGroup(packedPosition);
if (mAdapter.getHeadViewClickStatus(groupPosition) == 1) {
this.collapseGroup(groupPosition);
mAdapter.onHeadViewClick(groupPosition, 0);
} else {
this.expandGroup(groupPosition);
mAdapter.onHeadViewClick(groupPosition, 1);
}
this.setSelectedGroup(groupPosition);
}
private float mDownX;
private float mDownY;
/**
* HeaderView , HeaderView, , HeaderView
* , , .
*/
@Override
public boolean onTouchEvent(MotionEvent ev) {
if (mHeaderViewVisible) {
switch (ev.getAction()) {
case MotionEvent.ACTION_DOWN:
mDownX = ev.getX();
mDownY = ev.getY();
if (mDownX <= mHeaderViewWidth && mDownY <= mHeaderViewHeight) {
return true;
}
break;
case MotionEvent.ACTION_UP:
float x = ev.getX();
float y = ev.getY();
float offsetX = Math.abs(x - mDownX);
float offsetY = Math.abs(y - mDownY);
// HeaderView , HeaderView , headerClick()
if (x <= mHeaderViewWidth && y <= mHeaderViewHeight
&& offsetX <= mHeaderViewWidth
&& offsetY <= mHeaderViewHeight) {
if (mHeaderView != null) {
headerViewClick();
}
return true;
}
break;
default:
break;
}
}
return super.onTouchEvent(ev);
}
@Override
public void setAdapter(ExpandableListAdapter adapter) {
super.setAdapter(adapter);
mAdapter = (IphoneTreeHeaderAdapter) adapter;
}
/**
*
* Group , Group
*/
@Override
public boolean onGroupClick(ExpandableListView parent, View v,
int groupPosition, long id) {
if (mAdapter.getHeadViewClickStatus(groupPosition) == 0) {
mAdapter.onHeadViewClick(groupPosition, 1);
parent.expandGroup(groupPosition);
parent.setSelectedGroup(groupPosition);
} else if (mAdapter.getHeadViewClickStatus(groupPosition) == 1) {
mAdapter.onHeadViewClick(groupPosition, 0);
parent.collapseGroup(groupPosition);
}
// true ,
return true;
}
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
super.onMeasure(widthMeasureSpec, heightMeasureSpec);
if (mHeaderView != null) {
measureChild(mHeaderView, widthMeasureSpec, heightMeasureSpec);
mHeaderViewWidth = mHeaderView.getMeasuredWidth();
mHeaderViewHeight = mHeaderView.getMeasuredHeight();
}
}
private int mOldState = -1;
@Override
protected void onLayout(boolean changed, int left, int top, int right,
int bottom) {
super.onLayout(changed, left, top, right, bottom);
final long flatPostion = getExpandableListPosition(getFirstVisiblePosition());
final int groupPos = ExpandableListView
.getPackedPositionGroup(flatPostion);
final int childPos = ExpandableListView
.getPackedPositionChild(flatPostion);
int state = mAdapter.getTreeHeaderState(groupPos, childPos);
if (mHeaderView != null && mAdapter != null && state != mOldState) {
mOldState = state;
mHeaderView.layout(0, 0, mHeaderViewWidth, mHeaderViewHeight);
}
configureHeaderView(groupPos, childPos);
}
public void configureHeaderView(int groupPosition, int childPosition) {
if (mHeaderView == null || mAdapter == null
|| ((ExpandableListAdapter) mAdapter).getGroupCount() == 0) {
return;
}
int state = mAdapter.getTreeHeaderState(groupPosition, childPosition);
switch (state) {
case IphoneTreeHeaderAdapter.PINNED_HEADER_GONE: {
mHeaderViewVisible = false;
break;
}
case IphoneTreeHeaderAdapter.PINNED_HEADER_VISIBLE: {
mAdapter.configureTreeHeader(mHeaderView, groupPosition,
childPosition, MAX_ALPHA);
if (mHeaderView.getTop() != 0) {
mHeaderView.layout(0, 0, mHeaderViewWidth, mHeaderViewHeight);
}
mHeaderViewVisible = true;
break;
}
case IphoneTreeHeaderAdapter.PINNED_HEADER_PUSHED_UP: {
View firstView = getChildAt(0);
int bottom = firstView.getBottom();
// intitemHeight = firstView.getHeight();
int headerHeight = mHeaderView.getHeight();
int y;
int alpha;
if (bottom < headerHeight) {
y = (bottom - headerHeight);
alpha = MAX_ALPHA * (headerHeight + y) / headerHeight;
} else {
y = 0;
alpha = MAX_ALPHA;
}
mAdapter.configureTreeHeader(mHeaderView, groupPosition,
childPosition, alpha);
if (mHeaderView.getTop() != y) {
mHeaderView.layout(0, y, mHeaderViewWidth, mHeaderViewHeight
+ y);
}
mHeaderViewVisible = true;
break;
}
}
}
@Override
/**
* ( )
*/
protected void dispatchDraw(Canvas canvas) {
super.dispatchDraw(canvas);
if (mHeaderViewVisible) {
// , ViewGroup
drawChild(canvas, mHeaderView, getDrawingTime());
}
}
@Override
public void onScroll(AbsListView view, int firstVisibleItem,
int visibleItemCount, int totalItemCount) {
final long flatPos = getExpandableListPosition(firstVisibleItem);
int groupPosition = ExpandableListView.getPackedPositionGroup(flatPos);
int childPosition = ExpandableListView.getPackedPositionChild(flatPos);
configureHeaderView(groupPosition, childPosition);
}
@Override
public void onScrollStateChanged(AbsListView view, int scrollState) {
}
}
사용 하기 도 간단 하 다.먼저 레이아웃 파일 에 activity 를 설명 한다.main.xml:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity" >
<com.way.iphonetreeview.IphoneTreeView
android:id="@+id/iphone_tree_view"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="@android:color/transparent"
android:cacheColorHint="@android:color/transparent"
android:divider="@null"
android:transcriptMode="normal" />
</RelativeLayout>
그리고 MainActivity 에서 호출 되 었 습 니 다.코드 를 줄 이기 위해 저 는 Adapter 를 내부 클래스 로 MainActivity 에 두 었 습 니 다
public class MainActivity extends Activity {
private LayoutInflater mInflater;
private IphoneTreeView iphoneTreeView;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
initView();
}
private void initView() {
// TODO Auto-generated method stub
mInflater = LayoutInflater.from(this);
iphoneTreeView = (IphoneTreeView) findViewById(R.id.iphone_tree_view);
iphoneTreeView.setHeaderView(getLayoutInflater().inflate(
R.layout.list_head_view, iphoneTreeView, false));
iphoneTreeView.setGroupIndicator(null);
iphoneTreeView.setAdapter(new IphoneTreeViewAdapter());
}
public class IphoneTreeViewAdapter extends BaseExpandableListAdapter
implements IphoneTreeHeaderAdapter {
// Sample data set. children[i] contains the children (String[]) for
// groups[i].
private HashMap<Integer, Integer> groupStatusMap;
private String[] groups = { " ", " ", " ", " " };
private String[][] children = {
{ "Way", "Arnold", "Barry", "Chuck", "David", "Afghanistan",
"Albania", "Belgium", "Lily", "Jim", "LiMing", "Jodan" },
{ "Ace", "Bandit", "Cha-Cha", "Deuce", "Bahamas", "China",
"Dominica", "Jim", "LiMing", "Jodan" },
{ "Fluffy", "Snuggles", "Ecuador", "Ecuador", "Jim", "LiMing",
"Jodan" },
{ "Goldy", "Bubbles", "Iceland", "Iran", "Italy", "Jim",
"LiMing", "Jodan" } };
public IphoneTreeViewAdapter() {
// TODO Auto-generated constructor stub
groupStatusMap = new HashMap<Integer, Integer>();
}
public Object getChild(int groupPosition, int childPosition) {
return children[groupPosition][childPosition];
}
public long getChildId(int groupPosition, int childPosition) {
return childPosition;
}
public int getChildrenCount(int groupPosition) {
return children[groupPosition].length;
}
public Object getGroup(int groupPosition) {
return groups[groupPosition];
}
public int getGroupCount() {
return groups.length;
}
public long getGroupId(int groupPosition) {
return groupPosition;
}
public boolean isChildSelectable(int groupPosition, int childPosition) {
return true;
}
public boolean hasStableIds() {
return true;
}
@Override
public View getChildView(int groupPosition, int childPosition,
boolean isLastChild, View convertView, ViewGroup parent) {
// TODO Auto-generated method stub
if (convertView == null) {
convertView = mInflater.inflate(R.layout.list_item_view, null);
}
TextView tv = (TextView) convertView
.findViewById(R.id.contact_list_item_name);
tv.setText(getChild(groupPosition, childPosition).toString());
TextView state = (TextView) convertView
.findViewById(R.id.cpntact_list_item_state);
state.setText(" ... Android...");
return convertView;
}
@Override
public View getGroupView(int groupPosition, boolean isExpanded,
View convertView, ViewGroup parent) {
// TODO Auto-generated method stub
if (convertView == null) {
convertView = mInflater.inflate(R.layout.list_group_view, null);
}
TextView groupName = (TextView) convertView
.findViewById(R.id.group_name);
groupName.setText(groups[groupPosition]);
ImageView indicator = (ImageView) convertView
.findViewById(R.id.group_indicator);
TextView onlineNum = (TextView) convertView
.findViewById(R.id.online_count);
onlineNum.setText(getChildrenCount(groupPosition) + "/"
+ getChildrenCount(groupPosition));
if (isExpanded) {
indicator.setImageResource(R.drawable.indicator_expanded);
} else {
indicator.setImageResource(R.drawable.indicator_unexpanded);
}
return convertView;
}
@Override
public int getTreeHeaderState(int groupPosition, int childPosition) {
final int childCount = getChildrenCount(groupPosition);
if (childPosition == childCount - 1) {
return PINNED_HEADER_PUSHED_UP;
} else if (childPosition == -1
&& !iphoneTreeView.isGroupExpanded(groupPosition)) {
return PINNED_HEADER_GONE;
} else {
return PINNED_HEADER_VISIBLE;
}
}
@Override
public void configureTreeHeader(View header, int groupPosition,
int childPosition, int alpha) {
// TODO Auto-generated method stub
((TextView) header.findViewById(R.id.group_name))
.setText(groups[groupPosition]);
((TextView) header.findViewById(R.id.online_count))
.setText(getChildrenCount(groupPosition) + "/"
+ getChildrenCount(groupPosition));
}
@Override
public void onHeadViewClick(int groupPosition, int status) {
// TODO Auto-generated method stub
groupStatusMap.put(groupPosition, status);
}
@Override
public int getHeadViewClickStatus(int groupPosition) {
if (groupStatusMap.containsKey(groupPosition)) {
return groupStatusMap.get(groupPosition);
} else {
return 0;
}
}
}
}
자,간단 한 예 를 들 어 완 성 했 습 니 다.정리 하 겠 습 니 다.원리:표시 되 고 있 는 맨 위 그룹의 태그 위치 에 그룹 보기 와 똑 같은 보 기 를 추가 하여 그룹 태그 로 합 니 다.이 탭 의 위 치 는 목록 이 미 끄 러 지면 서 항상 맨 위 에 표시 되 고 사라 질 때 사라 집 니 다.이 탭 에 클릭 이 벤트 를 추가 하여 그룹 을 열 고 닫 는 기능 을 수행 합 니 다.그룹 탭 은 항상 위 에 표 시 됩 니 다.이것 은 레이아웃 에 있 는 위 치 를 계속 조정 함으로써 이 루어 집 니 다.이 조정 과정 은 초기 화 할 때 onLayout 방법 에서 한 번 이 루어 집 니 다.그 다음은 스크롤 과정 에서 스크롤 상태 에 대한 감청 에 따라 이 루어 집 니 다.추가 할 탭 을 실례 화 할 때(밖에서 이 루어 지 더 라 도 setTreeHeaderView 를 호출 하기 전에)parent 는 이 ExpandableListView 로 설정 합 니 다.이것 을 배우 고 잘 이해 하려 면 추 가 된 그룹 탭 을 반투명 으로 설정 하여 전체 과정 을 관찰 하 는 것 이 가장 좋 습 니 다원본 코드 다운로드