java - 如果可扩展布局超出屏幕,则 ScrollView 显示布局
问题描述
我的 Android 应用程序中有几个可扩展的布局。当我单击展开布局时,布局会在屏幕外消失,我必须手动向下滚动以使其可见。如何使 ScrollView 自动向下滚动以使单击的布局可见?
我尝试使用scrollView.scrollTo(0, textID.getBottom());
滚动到布局元素的底部,但没有运气。
爪哇:
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
推荐阅读
- android - 无法将 JSONArray 转换为列表 (Kotlin)
- javascript - 按字符串与数值排序对象数组表现不同
- swift - 如何使用 swift 同步核心音频的输入和播放
- mysql - 当主键设置为 AUTO_INCREMENT 时,有没有办法停止在 n 处增加行?
- java - Java中的“大于”或“小于”的正则表达式,不使用括号“<|>”符号
- python - 在python中用冒号替换空格
- regex - Bash:如何在某些行中排除某些行?
- mysql - 如何在 MySQL 中交叉两个查询
- git - 启用 GPG 签名的交互式 rebase 失败
- c - 了解洗牌功能