【问题标题】:Add a View on top of a ListView and move everything when scrolling down?在 ListView 顶部添加一个视图并在向下滚动时移动所有内容?
【发布时间】:2015-01-04 12:12:31
【问题描述】:

我想在列表视图的顶部添加一个视图操作(我们称之为标题)。当用户向下滚动时,我希望所有内容都向上移动(包括标题)。然而,现在当用户滚动时,标题保持固定在顶部(如 CSS 上的“位置:固定”),而不是与其余内容一起滚动。

如何让用户滚动所有内容而不仅仅是 ListView 的内容?

这就是我现在的布局:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:background="?attr/color2">

<TextView
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:id="@+id/header"
    style="@style/header"
    android:drawableLeft="@drawable/ic_setup"
    android:text="@string/fragment_contacts"/>


<ListView android:id="@android:id/list"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:drawSelectorOnTop="false"
    android:fastScrollEnabled="false">

</ListView>

</LinearLayout>

【问题讨论】:

    标签: android listview


    【解决方案1】:

    my_layout_header.xml

    这是列表标题的 XML 布局。

    <?xml version="1.0" encoding="utf-8"?>
    <TextView
      xmlns:android="http://schemas.android.com/apk/res/android"
      android:layout_width="wrap_content"
      android:layout_height="wrap_content"
      android:drawableLeft="@drawable/ic_setup"
      android:text="@string/fragment_contacts" />
    

    my_layout.xml

    这是主要布局。

    <?xml version="1.0" encoding="utf-8"?>
    <ListView
      xmlns:android="http://schemas.android.com/apk/res/android"
      android:layout_width="match_parent"
      android:layout_height="match_parent"
      android:id="@android:id/list"
      android:drawSelectorOnTop="false"
      android:fastScrollEnabled="false" />
    

    代码

    现在您需要将标题布局 XML 扩展为 View 并将其设置为您的 ListView 的标题视图。可以在Activity.onCreate(Bundle) 中使用以下 sn-p:

    setContentView(R.layout.my_layout);
    
    View header = View.inflate(this, R.layout.my_layout, null);
    // where "this" is a context / activity...
    
    ListView list = (ListView)findViewById(android.R.id.list);
    list.addHeaderView(header, null, false); // header will not be clickable
    // ... whatever else you need to do AFTER you set a header (a bug before KITKAT) ...
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2021-04-25
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-12-17
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多