相信做前端的都做过页面锚点定位的功能,通过<a href="#head"> 去设置页面内锚点定位跳转。

本篇文章就使用tablayoutscrollview来实现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);
} }

布局文件里 tablayoutCustomScrollView,内容暂时使用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"
android:layout_height="match_parent"
android:orientation="vertical"> <android.support.design.widget.TabLayout
android:id="@+id/tablayout"
android:layout_width="match_parent"
android:layout_height="wrap_content"
app:tabIndicatorColor="@color/colorPrimary"
app:tabMode="scrollable"
app:tabSelectedTextColor="@color/colorPrimary" /> <com.tabscroll.CustomScrollView
android:id="@+id/scrollView"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:fillViewport="true"
android:fitsSystemWindows="true"> <LinearLayout
android:id="@+id/container"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical"
android:padding="16dp"> </LinearLayout> </com.tabscroll.CustomScrollView> </LinearLayout>

数据模拟

数据模拟,动态添加scrollview内的内容,这里自定义了AnchorView当作每一块的填充内容。

private String[] tabTxt = {"客厅", "卧室", "餐厅", "书房", "阳台", "儿童房"};
//内容块view的集合
private List<AnchorView> anchorList = new ArrayList<>();
//判读是否是scrollview主动引起的滑动,true-是,false-否,由tablayout引起的
private boolean isScroll;
//记录上一次位置,防止在同一内容块里滑动 重复定位到tablayout
private int lastPos; //模拟数据,填充scrollview
for (int i = 0; i < tabTxt.length; i++) {
AnchorView anchorView = new AnchorView(this);
anchorView.setAnchorTxt(tabTxt[i]);
anchorView.setContentTxt(tabTxt[i]);
anchorList.add(anchorView);
container.addView(anchorView);
} //tablayout设置标签
for (int i = 0; i < tabTxt.length; i++) {
tabLayout.addTab(tabLayout.newTab().setText(tabTxt[i]));
}

定义变量标志isScroll,用于判断scrollview的滑动由谁引起的,避免通过点击tabLayout引起的scrollview滑动问题。

定义变量标志lastPos,当scrollview 在同一模块中滑动时,则不再去调用tabLayout.setScrollPosition刷新标签。

自定义的AnchorView

public class AnchorView extends LinearLayout {

    private TextView tvAnchor;
private TextView tvContent; public AnchorView(Context context) {
this(context, null);
} public AnchorView(Context context, @Nullable AttributeSet attrs) {
this(context, attrs, 0);
} public AnchorView(Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
init(context);
} private void init(Context context) {
View view = LayoutInflater.from(context).inflate(R.layout.view_anchor, this, true);
tvAnchor = view.findViewById(R.id.tv_anchor);
tvContent = view.findViewById(R.id.tv_content);
Random random = new Random();
int r = random.nextInt(256);
int g = random.nextInt(256);
int b = random.nextInt(256);
tvContent.setBackgroundColor(Color.rgb(r, g, b));
} public void setAnchorTxt(String txt) {
tvAnchor.setText(txt);
} public void setContentTxt(String txt) {
tvContent.setText(txt);
}
}

实现

scrollview的滑动监听:

scrollView.setOnTouchListener(new View.OnTouchListener() {
@Override
public boolean onTouch(View v, MotionEvent event) {
//当由scrollview触发时,isScroll 置true
if (event.getAction() == MotionEvent.ACTION_DOWN) {
isScroll = true;
}
return false;
}
}); scrollView.setCallbacks(new CustomScrollView.Callbacks() {
@Override
public void onScrollChanged(int x, int y, int oldx, int oldy) {
if (isScroll) {
for (int i = tabTxt.length - 1; i >= 0; i--) {
//根据滑动距离,对比各模块距离父布局顶部的高度判断
if (y > anchorList.get(i).getTop() - 10) {
setScrollPos(i);
break;
}
}
}
}
}); //tablayout对应标签的切换
private void setScrollPos(int newPos) {
if (lastPos != newPos) {
//该方法不会触发tablayout 的onTabSelected 监听
tabLayout.setScrollPosition(newPos, 0, true);
}
lastPos = newPos;
}

tabLayout的点击切换:

tabLayout.addOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
@Override
public void onTabSelected(TabLayout.Tab tab) {
//点击标签,使scrollview滑动,isScroll置false
isScroll = false;
int pos = tab.getPosition();
int top = anchorList.get(pos).getTop();
scrollView.smoothScrollTo(0, top);
} @Override
public void onTabUnselected(TabLayout.Tab tab) { } @Override
public void onTabReselected(TabLayout.Tab tab) { }
});

至此效果出来了,但是

问题来了 可以看到当点击最后一项时,scrollView滑动到底部时并没有呈现出我们想要的效果,希望滑到最后一个时,全屏只有最后一块内容显示。

所以这里需要处理下最后一个view的高度,当不满全屏时,重新设置他的高度,通过计算让其撑满屏幕。

//监听判断最后一个模块的高度,不满一屏时让最后一个模块撑满屏幕
private ViewTreeObserver.OnGlobalLayoutListener listener; listener = new ViewTreeObserver.OnGlobalLayoutListener() {
@Override
public void onGlobalLayout() {
int screenH = getScreenHeight();
int statusBarH = getStatusBarHeight(MainActivity.this);
int tabH = tabLayout.getHeight();
//计算内容块所在的高度,全屏高度-状态栏高度-tablayout的高度-内容container的padding 16dp
int lastH = screenH - statusBarH - tabH - 16 * 3;
AnchorView lastView = anchorList.get(anchorList.size() - 1);
//当最后一个view 高度小于内容块高度时,设置其高度撑满
if (lastView.getHeight() < lastH) {
LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT);
params.height = lastH;
lastView.setLayoutParams(params);
}
container.getViewTreeObserver().removeOnGlobalLayoutListener(listener); }
};
container.getViewTreeObserver().addOnGlobalLayoutListener(listener);

这样就达到了预期的效果了。

写到这里,tablayout + scrollview的锚点定位成型了,在实际项目中,我们还可以使用tablayout + recyclerview 来完成同样的效果,后续的话会带来这样的文章。

这段时间自己在做一个小程序,包括数据爬取 + 后台 + 小程序的,可能要过段时间才能出来,主要是数据爬虫那边比较麻烦的...期待下!

详细代码见

github地址:https://github.com/taixiang/tabScroll

欢迎关注我的博客:https://blog.manjiexiang.cn/

更多精彩欢迎关注微信号:春风十里不如认识你

有个「佛系码农圈」,欢迎大家加入畅聊,开心就好!



过期了,可加我微信 tx467220125 拉你入群。

Android 实现锚点定位的更多相关文章

  1. Android tabLayout+recyclerView实现锚点定位

    原文链接:https://mp.weixin.qq.com/s/L3o2i3WTmg1ScXEYDS8YCg 在上一篇文章 Android 实现锚点定位中,我们介绍了tablayout+scrollV ...

  2. html中设置锚点定位的几种常见方法(#号定位)

    在html中设置锚点定位我知道的有几种方法,在此和大家分享一下: 1.使用id定位: <a href="#1F">锚点1</a> <div id=&q ...

  3. 【TRICK】解决锚点定位向下浮动Xpx问题

    1. 问题描述 页面滚动后,菜单栏会固定在页头,当锚点定位时,菜单会遮盖部分定位后的内容,所以需要在锚点定位后自动向下漂移Xpx. 2. 解决办法 a. 利用空div 占位,如下: <a hre ...

  4. 当锚点定位遇上position: fixed

    <!DOCTYPE html><html> <head> <title>当锚点定位遇上position: fixed</title> < ...

  5. 锚点定位,jquery定位到页面指定位置

    jquery锚点定位 $('body,html').animate({scrollTop: $('#ter1').offset().top}, 500);#ter1是你要定位的id对象,500是0.5 ...

  6. js实现锚点定位

    js实现锚点定位的原理是,算出定位的标签距离顶部的高度,点击触发标签,重新赋值滚动条的高度到达指定位置. <!DOCTYPE html> <html> <head> ...

  7. html锚点定位不准确问题

    问题描述 当顶部固定时,点击锚点,会跳转到锚点以下. <style> #one,#two,#three{ height: 500px; } #top{ position: fixed; h ...

  8. 微信小程序基于scroll-view实现锚点定位

    代码地址如下:http://www.demodashi.com/demo/14009.html 一.前期准备工作 软件环境:微信开发者工具 官方下载地址:https://mp.weixin.qq.co ...

  9. html 锚点定位

    在html中设置锚点定位我知道的有几种方法.在此和大家分享一下: 1.使用id定位: <a href="#1F" name="1F">锚点1< ...

随机推荐

  1. Powermock2.0.0 详细 总结

    目录 1 单元测试 2 Junit测试框架 2.1 Junit是什么 2.2 Junit 能做什么? 3 Junit测试的局限性 4 Mock技术 5 相关的Mock工具 5.1 Mockito.Ea ...

  2. Python图像处理库PIL中图像格式转换

    o 在数字图像处理中,针对不同的图像格式有其特定的处理算法.所以,在做图像处理之前,我们需要考虑清楚自己要基于哪种格式的图像进行算法设计及其实现.本文基于这个需求,使用python中的图像处理库PIL ...

  3. Spring Cloud是怎么运行的?

    导读 在之前的文章中给大家介绍了Spring Boot的基本运行原理(链接),收到了很多读者朋友们关于目前比较流行的微服务框架Spring Cloud的问题反馈.因此,在这篇文章中小码哥打算和大家一起 ...

  4. Number(),parseInt(),parseFloat(),Math.round(),Math.floor(),Math.ceil()对比横评

    首先,这些处理方法可分为三类. 1,只用来处理数字取整问题的:Math.round(),Math.floor(),Math.ceil(): 2,专门用于把字符串转化成数值:parseInt(),par ...

  5. 2014--My Plan

    写于2014/1/10 从2014年开始我每年规划自己的life,每年10个plans. 回忆2013: 2013年,改变了很多.准确的说,那10个月,像个漫长的旅程,像个人生的转折点,应该可以这么说 ...

  6. Chapter 4 Invitations——7

    The next day, I was surprised that Jessica wasn't her usual gushing self in Trig and Spanish. 第二天,我很 ...

  7. Dockerfile 时区设置

    RUN ln -sf /usr/share/zoneinfo/Asia/Shanghai /etc/localtime RUN echo 'Asia/Shanghai' >/etc/timezo ...

  8. Hadoop YARN架构设计要点

    YARN是开源项目Hadoop的一个资源管理系统,最初设计是为了解决Hadoop中MapReduce计算框架中的资源管理问题,但是现在它已经是一个更加通用的资源管理系统,可以把MapReduce计算框 ...

  9. 第8章 CentOS包管理详解

    8.1 Linux上构建C程序的过程 在说明包相关的内容之前,我觉得有必要说一下在Linux上构建一个C程序的过程.我个人并没有学习过C,内容总结自网上,所以可能显得很小白,而且也并非一定正确,只希望 ...

  10. js_ajax模拟form表单提交_多文件上传_支持单个删除

    需求场景: 用一个input type="file"按钮上传多张图片,可多次上传,可单独删除,最后使用ajax模拟form表单提交功能提交到指定方法中: 问题:由于只有一个file ...