簡體   English   中英

Android-ListActivity,添加頁眉和頁腳視圖

[英]Android - ListActivity, add Header and Footer view

我正在使用ListActivity,listview。

listView = getListView();

完美地工作。 我添加了頁腳視圖為

LayoutInflater inflater = getLayoutInflater();
listView.addFooterView( inflater.inflate( R.layout.footer, null ), null, false);

而且一切都很閃亮但很丑陋,所以我想將此頁腳視圖(僅包含1個edittext和僅1個button)添加到listView的標頭中,如下所示:

LayoutInflater inflater = getLayoutInflater();
listView.addHeaderView( inflater.inflate( R.layout.footer, null ), null, false);

突然一切都出錯了,我立即得到RuntimeException。

Suspended(exception RuntimeException)
ActivityThread.performLaunchActivity(ActivityThread$ActivityRecord, Intent)
ActivityThread.handleLaunchActivity(ActivityThread$ActivityRecord, Intent)
ActivityThread.access$2200(ActivityThread, Activity$ActiviyRecord, Intent),
so on..

為什么會引發異常? addFooterView和addHeaderView有什么區別,如何將Header添加到ListActivity?

UPDATE

因此,如您所見,我的logcat仍然無法正常工作,但此刻我只是嘗試了一下:

} catch(Exception e){ 
  Writer result = new StringWriter(); 
  PrintWriter printWriter = new PrintWriter(result);
  e.printStackTrace(printWriter);
  String error = result.toString(); 
}

然后我放斷點,我可以在表達式部分讀取錯誤。 它說 :

java.lang.IllegalStateException: Cannot add header view to list -- setAdapter has already been called. 

這對我們所有人都是有益的。 更改各種命令后,它可以正常工作。

當您登錄時

java.lang.IllegalStateException:無法將標頭視圖添加到列表中-已經調用了setAdapter。

ListView的方法addHeaderViewaddFooterView必須setAdapter之前被調用。

為頁眉和頁腳創建布局xml

header_layout.xml

 <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent" >
    <TextView
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:gravity="center_horizontal"
    android:text="header"
    />
    </RelativeLayout>

footer_layout.xml

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent" >
<TextView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:gravity="center_horizontal"
android:text="footer"
/>
</RelativeLayout>

現在處於活動狀態的java文件onCreate()方法添加

listView = (ListView) findViewById(R.id.listView1);
LayoutInflater inflater = getLayoutInflater();
    ViewGroup header = (ViewGroup) inflater.inflate(R.layout.header, listView,
            false);
    ViewGroup footer = (ViewGroup) inflater.inflate(R.layout.footer, listView,
            false);
    listView.addHeaderView(header, null, false);
    listView.addFooterView(footer, null, false);
    listView.setAdapter(adapter);

因此,如果要將標題視圖添加到listView,則應在使用setListAdapter()之前嚴格執行此操作,否則會導致IllegalStateException。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM