2016-04-10 32 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,但感谢您的努力。 –