源码地址 http://download.csdn.net/detail/zhangjm_123/7902245
最近写了一个fragment+viewpager仿qq的app,先上图
如图,界面底部有四个textview,分别是消息、好友、动态、我的,每点击一个textview将会将会到相应的fragment。大家可能注意到第1张图片和其它的不一样。事实上,这4张图片都是fragment,只是第1张图片中的fragment里有一个viewpager,viewpager里面有3个view,分别为消息、通话、视频对应的view,这里为了区分开来,暂且用1、2、3来标识三者,用手指左右滑动viewpager或点击顶部的tab,就会分别切换消息、通话、视频界面,完整的应该如下:
代码没什么难度,在这里就不贴详细代码了,相对复杂一些的是当滑动MessageFragment时,顶部tab跟着滑动的代码:
首先,监听viewpager的OnPageChangeListener事件
<span style="font-size:14px;"></pre><pre name="code" class="java">viewPager.setOnPageChangeListener(this);</span>
当滑动完毕后,设置tab的滚动位置
<span style="font-size:14px;"> @Override
public void onPageSelected(int position) {
setCursorPosition(position);
}</span>
<span style="font-size:14px;"><span style="white-space:pre"> </span>private void setCursorPosition(int position) {
lastCursorPos = curCursorPos;
curCursorPos = position;
new Thread(cursorPosRunnable).start();//开一个线程,用于滚动tab
}</span>
<span style="font-size:14px;"><span style="white-space:pre"> </span>cursorPosRunnable = new Runnable() {
@Override
public void run() {
calcXAndSendMsg();
}
private void calcXAndSendMsg() {
try{
int cusorCurrentX = titleTxtWidth*lastCursorPos+(titleTxtWidth-cursorWidth)/2;
int cursorTargetX = titleTxtWidth*curCursorPos+(titleTxtWidth-cursorWidth)/2;
if(lastCursorPos == curCursorPos) {
handler.obtainMessage(WHAT_SET_CURSOR_POSITION, cusorCurrentX, 0).sendToTarget();
} else {
while(cusorCurrentX != cursorTargetX) {
if(cusorCurrentX < cursorTargetX) {
cusorCurrentX+=15;
} else {
cusorCurrentX-=15;
}
handler.obtainMessage(WHAT_SET_CURSOR_POSITION, cusorCurrentX, 0).sendToTarget();
Thread.sleep(5);
}
}
}catch(InterruptedException e) {
e.printStackTrace();
}
}
};</span>
<span style="font-size:14px;"><span style="white-space:pre"> </span>//接收cursorPosRunnable发送过来的消息,并设置tab的x坐标,实现滚动效果
handler = new Handler() {
public void handleMessage(Message msg) {
switch (msg.what) {
case MessageFragment.WHAT_SET_CURSOR_POSITION:
cursorView.setX(msg.arg1);
break;
default:
break;
}
};
};</span>
具体看下载源码看看 http://download.csdn.net/detail/zhangjm_123/7902245