因为工作上的需求,要实现一个翻页的页面,入下图:
刚开始看到这种页面,想过viewpager,不过后来想换别的方式,所以想过gridview,但是gridview无法翻页,所以试了不行。后来想到了HorizontalScrollView这个控件。然后就试了一下,感觉还可以,基本上滑动的功能差不多了,就差翻页的功能,所以就上网查了很多资料。终于查到pageScroll这个方法,看看上面的介绍:
简单来说,通过这个方法可以实现向左或者向右翻页,所以后来自己就有思路了,可以在onTouchListener中,监听x坐标来判断,用户是向左还是向右滑动,核心代码如下:
/*int position=sections.size()%3==0?sections.size()/3:sections.size()/3+1; //这里因为是刚好每一页三列,所以需要这么计算
WindowManager wm=(WindowManager) getSystemService(Context.WINDOW_SERVICE);
int width=wm.getDefaultDisplay().getWidth();
int height=wm.getDefaultDisplay().getHeight();
for(int i=0;i<position;i++)
{
View convertView=getLayoutInflater().inflate(R.layout.topicadd_item, null);
MarginLayoutParams mlp=new MarginLayoutParams(width/3, MarginLayoutParams.WRAP_CONTENT);
convertView.setLayoutParams(mlp);
TextView tv1=(TextView) convertView.findViewById(R.id.topic_add_tv1);
TextView tv2=(TextView) convertView.findViewById(R.id.topic_add_tv2);
TextView tv3=(TextView) convertView.findViewById(R.id.topic_add_tv3);
if(3*i<=sections.size()-1)
{
tv1.setText(sections.get(3*i));
tv1.setTag(sections.get(3*i));
tv1.setOnClickListener(this);
}
if(3*i+1<=sections.size()-1)
{
tv2.setText(sections.get(3*i+1));
tv2.setTag(sections.get(3*i+1));
tv2.setOnClickListener(this);
}else
{
tv2.setVisibility(View.INVISIBLE);
}
if((3*i+2)<=sections.size()-1)
{
tv3.setText(sections.get(3*i+2));
tv3.setTag(sections.get(3*i+2));
tv3.setOnClickListener(this);
}else
{
tv3.setVisibility(View.INVISIBLE);
}
lly.addView(convertView); //把item布局添加到HorizontalScrollView的子布局中
}*/
在onTouchListener的onTouch方法中,判断:
public boolean onTouch(View v, MotionEvent event) {
float xDown = 0;
float xUp = 0;
switch(event.getAction())
{
case MotionEvent.ACTION_DOWN:
Log.e("TAG", "ACTION_DOWN");
xDown=event.getX();
break;
case MotionEvent.ACTION_UP:
Log.e("TAG", "ACTION_UP");
xUp=event.getX();
if(xUp-xDown>0)
{
hsv.pageScroll(View.FOCUS_RIGHT);//向左翻页
}else
{
hsv.pageScroll(View.FOCUS_LEFT);
}
break;
}
return true;
}
核心代码基本是这样。不过因为在onTouch方法中ACTION_DOWN始终拦截不到,最终还是放弃了。采用viewpager轻松实现了。后面再补充吧。