在做一个小项目时遇到需要随着手势翻页的同时,上面导航栏也需要随着而滑动,这样就需要在手势事件中调用滚动条的水平滑动事件。
总体效果图如下:
滚动部分布局XML片段:
<HorizontalScrollView
android:id="@+id/horizonMenu"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:scrollbars="none" >
<LinearLayout
android:id="@+id/chart_navigate"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_alignParentLeft="true"
android:layout_gravity="top"
android:background="#ffffff"
android:orientation="horizontal"
android:layout_margin="0dp"
android:layout_marginBottom="1dip"
android:padding="0dp">
</LinearLayout>
</HorizontalScrollView>
部分代码:
/**
* the layout of chart.
*
* @author liangliu
*
*/
public class ChartFramgment extends Fragment {
private static View viewMain;
// the loading dialog after completed to login
private static LinearLayout linearLayout;
private static int navigateWidth = 0;
private static HorizontalScrollView horizontalScrollView;
private final static Handler handler = new Handler();
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
super.onCreateView(inflater, container, savedInstanceState);
// get the view by id in the framgment.
viewMain = inflater.inflate(R.layout.chart, container, false);
DisplayMetrics displaymetrics = new DisplayMetrics();
getActivity().getWindowManager().getDefaultDisplay()
.getMetrics(displaymetrics);
navigateWidth=(int)(displaymetrics.widthPixels*0.8);
horizontalScrollView = (HorizontalScrollView) viewMain
.findViewById(R.id.horizonMenu);
horizontalScrollView
.setLayoutParams(new android.widget.RelativeLayout.LayoutParams(
navigateWidth, 100));
linearLayout = (LinearLayout) viewMain
.findViewById(R.id.chart_navigate);
linearLayout.setOrientation(LinearLayout.HORIZONTAL);
return viewMain;
}
/**
* 手势事件,滑动到下一页
*/
public static void slipToNext() {
//滑动到下一页d的相关处理
//......
//导航滚动条随着水平滚动 ,这里必须放到handler里面异步处理滚动才会到位,否则滚动会是上次滚动的结果,总差那么一点。
handler.post(scrollHandler);
}
/**
* slip back to the pre_page
*/
public static void slipToBack() {
//滑动到上一页d的相关处理
//......
//导航滚动条随着水平滚动
handler.post(scrollHandler);
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
private static Runnable scrollHandler = new Runnable() {
@Override
public void run() {
//计算滚动偏移量
int offSet = (linearLayout.getMeasuredWidth())
- horizontalScrollView.getWidth();
if (offSet < 0) {
offSet = 0;
}
//滑到制定位置
horizontalScrollView.scrollTo(offSet, 0);
}
};
}
以上是水平自动滚动的部分代码,垂直类似,做对应改动即可。