【发布时间】:2016-03-20 19:10:26
【问题描述】:
我注意到 Google 应用中有一些非常有用的东西。
当我们有大内容的对话框时,会显示分隔线以强调滚动能力,就像这两张图片:
但是,我不知道如何使用已知的工具来实现这种行为。
最好的例子是在选择电话铃声时,一开始底部只有一个分隔线,但是当我们开始滚动时会出现两个分隔线。
问题
如何实现对话框中出现和消失的行为?
【问题讨论】:
我注意到 Google 应用中有一些非常有用的东西。
当我们有大内容的对话框时,会显示分隔线以强调滚动能力,就像这两张图片:
但是,我不知道如何使用已知的工具来实现这种行为。
最好的例子是在选择电话铃声时,一开始底部只有一个分隔线,但是当我们开始滚动时会出现两个分隔线。
问题
如何实现对话框中出现和消失的行为?
【问题讨论】:
如果你有这样的自定义布局
<?xml version="1.0" encoding="utf-8"?>
<ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/scroll_container"
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="1">
<LinearLayout
android:id="@+id/views_container"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical" />
</ScrollView>
你可以通过inflate View 找到ScrollView
v.findViewById(R.id.scroll_container)
如果您的自定义视图上方有 TITLE 和下方有 BUTTONS,则设置滚动 TOP 和 BOTTOM 指示器
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
final int indicators = View.SCROLL_INDICATOR_TOP | View.SCROLL_INDICATOR_BOTTOM;
scrollView.setScrollIndicators(indicators, View.SCROLL_INDICATOR_TOP | View.SCROLL_INDICATOR_BOTTOM);
}
【讨论】:
您想要实现的行为带有Dialog with Scrollable Content。请阅读this document 了解这一点。
在这种情况下,您需要使用ListView 和几个按钮创建自己的自定义布局xml。而且您需要将整个布局保留在ScrollView 下。
以下只是帮助您的虚拟代码:
用实际代码编辑了虚拟代码::
layout.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_height="wrap_content"
android:layout_width="match_parent">
<ListView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/ListView"/>
</LinearLayout>
MainActivity.class:
LayoutInflater inflater= LayoutInflater.from(this);
view=inflater.inflate(R.layout.layout, null);
ListView listView = (ListView)view.findViewById(R.id.ListView);
String[] items = { "Milk", "Butter", "Yogurt", "Toothpaste", "Ice Cream" };
ArrayAdapter adapter_dest = new ArrayAdapter(this,android.R.layout.simple_list_item_1,items);
listView.setAdapter(adapter_dest);
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle("Custom Dialog")
.setCancelable(false)
.setView(view)
.setPositiveButton("OK", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
dialog.cancel();
}
});
AlertDialog alert = builder.create();
alert.show();
希望这会有所帮助!
【讨论】:
ListView 的自定义布局,默认情况下可以滚动。不滚动它不会给出分隔线,但滚动它会产生效果。请检查我编辑的答案,然后让我知道需要改进的地方。 :)
查看 Android 源代码,解决方案非常简单。只需将此代码添加到您的自定义视图中:
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
final int indicators = (hasTopPanel() ? View.SCROLL_INDICATOR_TOP : 0)
| (hasBottomPanel() ? View.SCROLL_INDICATOR_BOTTOM : 0);
view.setScrollIndicators(indicators, View.SCROLL_INDICATOR_TOP | View.SCROLL_INDICATOR_BOTTOM);
}
【讨论】: