【问题标题】:How do I force Scrollview to start from the top of the child view?如何强制 Scrollview 从子视图的顶部开始?
【发布时间】:2015-12-09 07:38:38
【问题描述】:

我在横向布局中设置了一个简单的 ScrollView。当我将设备从纵向模式旋转到横向模式时,UI 屏幕会向下滚动一点,并且视图的最顶部不再可见。如何强制视图从视图顶部开始?我尝试设置“mScrollView.scrollTo(0,0);”以编程方式但没有运气。请指教。

部分土地\layout.xml文件:

<?xml version="1.0" encoding="utf-8"?>

<LinearLayout

xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#FFFFFF"
android:focusableInTouchMode="true"
tools:context=".CardViewActivity">

<include
    android:id="@+id/toolbar"
    layout="@layout/toolbar" >
</include>

<ScrollView
    android:id="@+id/ScrollView1"
    android:layout_width="match_parent"
    android:layout_height="match_parent"  >

<LinearLayout
    android:id="@+id/LinearLayout1"
    style="@style/scrollbar_shape_style"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:background="@drawable/rounded_corner"
    android:layout_marginLeft="6dp"
    android:layout_marginStart="6dp"
    android:layout_marginRight="6dp"
    android:layout_marginEnd="6dp"
    android:layout_marginTop="6dp"
    android:layout_marginBottom="6dp"
    android:useDefaultMargins="false"
    android:orientation="vertical"
    android:paddingRight="2dp"
    android:paddingEnd="2dp"  >

部分活动文件:

...
private ScrollView mScrollView;

@Override
protected void onResume() {
    super.onResume();
mScrollView = (ScrollView) findViewById(R.id.ScrollView1);
    if (mScrollView!=null) {
        mScrollView.setSmoothScrollingEnabled(false);
        mScrollView.fullScroll(ScrollView.FOCUS_UP);
        mScrollView.setSmoothScrollingEnabled(true);
    }
}

【问题讨论】:

    标签: android android-scrollview childviews


    【解决方案1】:

    在了解了背景之后,我建议对纵向也使用相同的布局和滚动视图。 Scrollview 会自动完成这项工作。

    【讨论】:

    • 我只在land\layout 文件中使用Scrollview。纵向布局文件不使用滚动视图。因此,当我在 Activity 中设置 mScrollView 时,它会崩溃——我认为是因为它试图在纵向布局上设置 mScrollView,并且在纵向布局中没有要设置的 ScrollView。我是否必须在 onResume 中设置 fullScroll 代码但使用某种类型的“if”语句仅在设备处于横向时才使用代码?
    • 您应该在使用 mScrollView 之前检查一下,就像这样 if (mScrollView!=null) { //do your stuff with mScrollView }
    • 我很抱歉。我刚刚接受了答案。如果在Activity中设置了mScrollView,“!null”如何否定在纵向模式下使用的mScrollView?
    • mScrollView = (ScrollView) findViewById(R.id.ScrollView1); 当你得到mScrollView时,如果找不到,函数会返回null,这是Java中Object的一种特殊状态,意思是没什么。 != 表示不相等,所以整个语句mScrollView != null 表示它不是nothing,在竖屏模式下,由于您尚未在布局中定义视图,mScrollView 将设置为null ,但是当您每次检查时,您不会尝试对其进行处理,这会导致错误。
    • 好的,我把fullScroll的代码放到onResume方法里。我在上面编辑了我的问题以显示 onResume 部分。我测试过,它不起作用。我也试过“scrollTo(0,0)”,但也没有用。想法?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-07-28
    • 1970-01-01
    • 1970-01-01
    • 2013-05-28
    相关资源
    最近更新 更多