Android 实现锚点定位思路详解实现锚点定位思路详解
相信做前端的都做过页面锚点定位的功能,通过<a href="#head" rel="external nofollow" > 去设置页面内锚点定位跳转。
本篇文章就使用tablayout、scrollview来实现android锚点定位的功能。
效果图:
实现思路实现思路
1、监听scrollview滑动到的位置,tablayout切换到对应标签
2、tablayout各标签点击,scrollview可滑动到对应区域
自定义scrollview
因为我们需要监听到滑动过程中scrollview的滑动距离,自定义scrollview通过接口暴露滑动的距离。
public class CustomScrollView extends ScrollView {
public Callbacks mCallbacks;
public CustomScrollView(Context context) {
super(context);
}
public CustomScrollView(Context context, AttributeSet attrs) {
super(context, attrs);
}
public CustomScrollView(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
}
public void setCallbacks(Callbacks callbacks) {
this.mCallbacks = callbacks;
}
@Override
protected void onScrollChanged(int l, int t, int oldl, int oldt) {
super.onScrollChanged(l, t, oldl, oldt);
if (mCallbacks != null) {
mCallbacks.onScrollChanged(l, t, oldl, oldt);
}
}
//定义接口用于回调
public interface Callbacks {
void onScrollChanged(int x, int y, int oldx, int oldy);
}
}
布局文件里 tablayout 和 CustomScrollView,内容暂时使用LinearLayout填充。
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"