【问题标题】:Use list view with headers in a layout with margins在带有边距的布局中使用带有标题的列表视图
【发布时间】:2016-04-10 19:38:53
【问题描述】:

我刚开始学习一点 Android。我目前正在尝试将列表视图与节标题一起使用。我在这个网站上找到了这个可重用的代码:

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

它使用两个布局文件:sn-p_item1.xmlsn-p_item2.xml

结果如下:

我希望这个页面从顶部有 100dp 的边距。我尝试将 margin_top 和 padding 添加到两个 xml 文件,但我没有得到想要的结果。

你怎么看?

【问题讨论】:

  • 您希望整个事物具有 100dp 的 margin_top 吗?只需将其添加到容器视图组中即可。
  • @m02ph3u5 不过这里没有容器。两种布局都在一个单独的文件中,不会出现在任何地方的容器中。我是不是误会了?
  • 不知道你是否可以用ListActivity 做到这一点,但尝试获取列表(它的 id 是list)并以编程方式添加边距。见developer.android.com/reference/android/app/ListActivity.html

标签: android listview layout header sections


【解决方案1】:

不是从 ListActivity 扩展,而是从一个简单的 Activity 扩展您的类,并在该 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 创建一个 Activity。

    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);
         }
    }

希望这能解决你的问题!

【讨论】:

    【解决方案2】:

    让我发布这个作为答案。不过,我不知道 ListActivity 是否可行。

    查看http://developer.android.com/reference/android/app/ListActivity.html了解更多详情。

    ListActivityListView 添加到 ID 为 list 的布局中。您可以尝试获取该列表并以编程方式添加边距。

    @Override
    public void onCreateView(...) {
        // set stuff up
    
        ListView lv = getListView();
        // set margin to lv
    }
    

    以编程方式设置填充/边距有点棘手,因为您必须将像素作为参数传递,但您需要 dp.但是您可以使用getResources().getDimensionPixelSize(R.style.youMarginStuffHere) 来处理它。只需将边距添加到您的 style.xml

    【讨论】:

    • 我无法使用您的方法 @m02ph3u5 但感谢您的努力。
    猜你喜欢
    • 1970-01-01
    • 2013-11-27
    • 1970-01-01
    • 2017-03-18
    • 1970-01-01
    • 2021-06-06
    • 1970-01-01
    • 2015-04-09
    • 2018-06-01
    相关资源
    最近更新 更多