2016-04-10 33 views
1

我剛開始學習一點Android。我目前正在嘗試使用帶節標題的列表視圖。我發現這個可重用的代碼在這個網站:使用列表視圖與邊緣佈局中的標題

http://javatechig.com/android/listview-with-section-header-in-android

它使用兩個佈局文件:snippet_item1.xmlsnippet_item2.xml

結果看起來是這樣的:

ListView with Section Headers

我想這個網頁有來自100dp的頂部空間。我曾嘗試將margin_top和padding添加到這兩個xml文件,但我沒有得到期望的結果。

您認爲如何?

+0

你希望整個事物的margin_top爲100dp?只需將其添加到容器視圖組。 – m02ph3u5

+0

@ m02ph3u5雖然這裏沒有容器。這兩種佈局都在單獨的文件中,並且不會出現在任何地方的容器中。我誤解了嗎? –

+0

不知道如果你可以用'ListActivity'來做到這一點,但嘗試獲取列表(它的id是'list')並以編程方式添加一個邊距。請參閱http://developer.android.com/reference/android/app/ListActivity.html – m02ph3u5

回答

1

不是從ListActivity擴展,而是從一個簡單的Activity擴展你的類,並在該活動中放置一個ListView,你可以給邊距和填充ListView。只需使用已經使用ListView創建的同一個適配器即可。這是如何。 這是您的活動的佈局文件,稱它爲activity_list.xml

<?xml version="1.0" encoding="utf-8"?> 
    <RelativeLayout 
     xmlns:android="http://schemas.android.com/apk/res/android" 
     android:orientation="vertical" 
     android:layout_width="match_parent" 
     android:layout_height="match_parent" 
     android:background="#fff"> 
    <ListView 
     android:layout_width="match_parent" 
     android:layout_height="match_parent" 
     android:marginTop="20sp" 
     android:marginBottom="10sp" 
     android:divider="@android:color/transparent" 
     android:id="@+id/listview" 
     android:padding="5sp" 
     android:dividerHeight="5.0sp" 
    ></ListView> 
    </RelativeLayout> 

現在在Java中創建一個活動。

public class MyListActivity extends Activity { 
     private ListView listView; 
     private MyAdapter myAdapter; 
     protected void onCreate(Bundle savedInstanceState) { 
       super.onCreate(savedInstanceState); 
       setContentView(R.layout.activity_list); 
       this.listView = (ListView) findViewById(R.id.listview); 
       this.myAdapter = new MyAdapter(getApplicationContext()); 
       //add whatever you want to add to your adapter 
       listView.setAdapter(myAdapter); 
     } 
    } 

我希望這可以解決您的問題!

+0

感謝隊友,這解決了它! –

0

讓我發表這個答案。不過,我不知道是否可以用ListActivity

檢查http://developer.android.com/reference/android/app/ListActivity.html瞭解更多詳情。

ListActivity在ID爲list的佈局中添加ListView。您可以嘗試抓取該列表並以編程方式添加邊距。

@Override 
public void onCreateView(...) { 
    // set stuff up 

    ListView lv = getListView(); 
    // set margin to lv 
} 

設置填充/保證金編程是有點棘手,你必須通過像素的說法,但你想要DP。但你可以使用getResources().getDimensionPixelSize(R.style.youMarginStuffHere)來處理。只需將保證金添加到您的style.xml即可。

+0

我無法使用您的方法@ m02ph3u5,但感謝您的努力。 –