You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Kotlin中实现ScrollView答题后自动上滚100px

Kotlin实现答题后ScrollView自动上滚100px的方案

1. 绑定ScrollView控件

首先在你的GamePlayFragment中获取布局里的ScrollView实例(你的布局中ScrollView的id为linearLayoutGame):

方式一:使用ViewBinding(推荐)

private lateinit var binding: GamePlayFragmentBinding

override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {
    binding = GamePlayFragmentBinding.inflate(inflater, container, false)
    return binding.root
}

方式二:传统findViewById

private lateinit var scrollView: ScrollView

override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {
    val view = inflater.inflate(R.layout.game_play_fragment, container, false)
    scrollView = view.findViewById(R.id.linearLayoutGame)
    return view
}

2. 实现自动滚动逻辑

在用户完成答题的回调(比如选项点击事件、答题提交逻辑)中,调用ScrollView的滚动方法:

平滑滚动(用户体验更友好)

// 在答题完成的逻辑里调用
binding.linearLayoutGame.smoothScrollBy(0, 100)
// 或者用findViewById的方式:scrollView.smoothScrollBy(0, 100)

瞬间滚动(无动画)

binding.linearLayoutGame.scrollBy(0, 100)

3. 适配屏幕密度(可选)

如果需要保证100px的滚动距离在不同分辨率设备上一致,建议将dp转换为像素:

// 工具方法:dp转像素
private fun dpToPx(dp: Int): Int {
    return (dp * resources.displayMetrics.density).toInt()
}

// 使用转换后的值
binding.linearLayoutGame.smoothScrollBy(0, dpToPx(100))

4. 注意事项

  • 确保ScrollView完成布局后再调用滚动方法,若在页面初始化时调用,需用post延迟执行:
    binding.linearLayoutGame.post {
        binding.linearLayoutGame.smoothScrollBy(0, dpToPx(100))
    }
    

内容的提问来源于stack exchange,提问作者ibrahim

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.01 06:55:22