Android,滚动所有元素:ImageViews、Textviews 和 ListViews

Android, Scroll all elements: ImageViews, Textviews and ListViews

Android 开发新手。我有一个页面(布局),其中包括 ImageView、TextView 和 ListView,我希望所有内容都是可滚动的。所以我将一个 Scrollview 作为所有容器的容器,但它不起作用,因为 ListView 不能放在 Scrollview 中。 以下是我的想法: 1) 有人说我可以将 ListView header 包含在 ImageView 和 TextView 中,但问题是我的 ListView 可能是空的...... 2)有没有其他观点,容器可以做类似的事情?例如,我不必使用 ListView,因为还有另一个类似的容器......? 谢谢, 帕特里克

ScrollView 是一个 FrameLayout,这意味着您应该在其中放置一个 child 包含要滚动的全部内容;这个 child 本身可能是一个具有复杂层次结构 objects 的布局管理器。尝试这样的事情:放置一个包含您的组件的 RelativeLayout 容器并将 RelativeLayout 放在 ScrollView 中。

<ScrollView android:layout_width="fill_parent"
android:layout_height="fill_parent"
xmlns:android="http://schemas.android.com/apk/res/android">

    <RelativeLayout>
     ...
     ...
     your components
     ...
    </RelativeLayout>
</ScrollView>

按此格式输入您的代码:

 <ScrollView
    android:id="@+id/scrollView1"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_alignParentTop="true"
    android:layout_centerHorizontal="true" >

    <RelativeLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content" >

        <ListView
            android:id="@+id/listView1"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_alignParentBottom="true"
            android:layout_centerHorizontal="true"
            android:layout_marginBottom="123dp" >
        </ListView>

        <TextView
            android:id="@+id/textView1"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginRight="71dp"
            android:layout_marginTop="48dp"
            android:text="Large Text"
            android:textAppearance="?android:attr/textAppearanceLarge" />
    </RelativeLayout>
</ScrollView>

您可以将 textView 和 imageView 放在单独的布局中,例如header.xml 并在某些控制器 class(activity 或片段)中将其设置为列表视图 header:

    ListView list = ListView.class.cast(findViewById(R.id.list));
    View header = getLayoutInflater().inflate(R.layout.header, null, false);
    list.addHeaderView(header);
    list.setAdapter(adapter());

但在此解决方案中,您应该设置适配器 after header view.

更新:

1) If my ListView is empty, is there a way to handle?

可以通过源适配器getCount()方法了解是否为空

2) The 'Header' will also scrollable with the whole page or stacked there?

Header 滚动为零列表视图项目(第一个)

我的代码和工作 `public class MainActivity 扩展了 ListActivity 实现 SearchView.OnQueryTextListener {

String name[]={"sajad","sara","mahya","fatemeyas","majid"};
ArrayAdapter<String> adapter;
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    adapter=new ArrayAdapter<String>(this,R.layout.activity_main, name);
    setListAdapter(adapter);
}`