2015-01-04 18 views
1

我想添加一個視圖操作頂部的列表視圖(我們稱之爲標題)。當用戶向下滾動時,我希望所有內容向上移動(包括標題)。然而,現在當用戶滾動頭部時,頭部會固定在頂部(如在CSS中的「position:fixed」),而不是滾動其餘內容。在向下滾動時在ListView頂部添加視圖並移動所有內容?

我該如何讓用戶滾動一切,而不僅僅是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> 

回答

5

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)內可以使用以下片段:

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) ... 
相關問題