问题描述
我的Android应用程序中有几种可扩展的布局。当我单击以展开布局时,该布局在屏幕外消失,并且我必须手动向下滚动以使其可见。如何使ScrollView自动向下滚动以使单击的布局可见?
我尝试使用scrollView.scrollTo(0,textID.getBottom());
滚动到布局元素的底部,但是没有运气。
Java:
expandableLayout1 = root.findViewById(R.id.expandable_layout1);
button = (LinearLayout)root.findViewById(R.id.Box_header);
button.setonClickListener(new View.OnClickListener(){
@Override
public void onClick(View view) {
if (expandableLayout1.isExpanded()) {
expandableLayout1.collapse();
} else {
expandableLayout1.expand();
scrollView.scrollTo(0,textID.getBottom());
}
}
});
xml:
<LinearLayout
android:id="@+id/Box"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<LinearLayout
android:id="@+id/Box_header"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="horizontal">
<TextView
android:id="@+id/textID"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="title"
android:textColor="#ffffff"
android:textSize="16sp"/>
</LinearLayout>
<net.cachapa.expandablelayout.ExpandableLayout
android:id="@+id/expandable_layout1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
app:el_duration="1000"
app:el_expanded="false"
app:el_parallax="0.5">
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="some text"
android:textColor="#ffffff"
android:textSize="12sp"/>
</net.cachapa.expandablelayout.ExpandableLayout>
</LinearLayout>
解决方法
您面临的问题是ExpandableLayout在ScrollView已经结束滚动到其底部之前没有时间完成打开。因此最终发生的是ScrollView滚动到尚未完全打开的ExpandableLayout的底部。您需要做的是在Layout打开和ScrollView启动滚动功能之间添加一个延迟。这是您需要的代码,我会尝试调整毫秒,您可以将其降低到1000以下,但幅度不大,仍然需要您自己解决一下问题,以使其更快,更流畅。还可以尝试使用smoothScrollTo而不是scrollTo。
expandableLayout1 = root.findViewById(R.id.expandable_layout1);
button = (LinearLayout)root.findViewById(R.id.box_header);
button.setOnClickListener(new View.OnClickListener(){
@Override
public void onClick(View view) {
if (expandableLayout1.isExpanded()) {
expandableLayout1.collapse();
} else {
expandableLayout1.expand();
new Handler().postDelayed(new Runnable() {
@Override
public void run() {
scrollView.post(new Runnable() {
@Override
public void run() {
scrollView.scrollTo(0,textID.getBottom());
}
});
}
},1000 ); // time in milliseconds
}
}
});
这是我以原始格式添加的代码,可能有助于您更轻松地理解它。
new Handler().postDelayed(new Runnable() {
@Override
public void run() {
// do something
}
},1000 ); // time in milliseconds