项目要求:一个十字架效果,水平和垂直滑动来选择每一子项。刚开始做的时候,以为很简单, 两个Gallery,一个水平,一个垂直放置就OK了,后来一看Gallery不能垂直滑动(网上貌似已经有了)。然后想为什么自己不能写一个了,花了两天功夫,终于做出效果来了,效果图如下:
1.代码目录结构
HVScrollbar.java:这个类负责承载每一个子项,其中有一个变量isVertical来判断水平或者垂直。
HVFrameLayout.java:这个类承载水平和垂直方向的滑动条,此类最关键的功能是控制滑动条的滑动,这点也是此功能的难点。
IconStyle.java:一个activity,不做介绍。
2.HVScrollbar.java
此类控制每一个子项的显示位置,并且显示水平或者垂直,在onMeasure和onLayout方法中控制。
@Override
protected void onLayout(boolean changed, int l, int t, int r, int b) {
// TODO Auto-generated method stub
FrameLayout.LayoutParams flp = (FrameLayout.LayoutParams)getLayoutParams();
int count = getChildCount();
for(int i = 0; i < count; i++)
{
View child = getChildAt(i);
ViewGroup.LayoutParams vlp = child.getLayoutParams();
if(vlp instanceof LayoutParams)
{
LayoutParams lp = (LayoutParams)vlp;
child.layout(lp.x, lp.y, lp.x + lp.width, lp.y+lp.height);//根据LayoutParams来布局
}
}
}
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
// TODO Auto-generated method stub
int count = getChildCount();
int widthSpecSize = 0;
int heightSpecSize = 0;
for (int i = 0; i < count; i++) {
View child = getChildAt(i);
ViewGroup.LayoutParams vlp = child.getLayoutParams();
if(vlp instanceof LayoutParams)
{
LayoutParams lp = (LayoutParams)vlp;
if(isVertical)
{
//垂直方向设置子项的top和left
lp.x = 0;
lp.y = lp.height * i;
widthSpecSize = lp.width;
heightSpecSize +=lp.height;
}
else
{
//水平方向设置子项的top和left
lp.y = 0;