Android: добавление статического заголовка в начало ListActivity - программирование
Подтвердить что ты не робот

Android: добавление статического заголовка в начало ListActivity

В настоящее время у меня есть класс, расширяющий класс ListActivity. Мне нужно добавить несколько статических кнопок над списком, которые всегда видны. Я попытался захватить ListView с помощью getListView() из класса. Затем я использовал addHeaderView (View), чтобы добавить макет в верхнюю часть экрана.

Header.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout  xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent" >
    <Button 
        android:id="@+id/testButton"
        android:layout_width="fill_parent" 
        android:layout_height="wrap_content"
        android:text="Income" 
        android:textSize="15dip"
        android:layout_weight="1" />
</LinearLayout>

Прежде чем установить адаптер, выполните следующие действия:

ListView lv = getListView();
lv.addHeaderView(findViewById(R.layout.header));

Это приводит к тому, что ничего не происходит с ListView, за исключением того, что он заполняется из моей базы данных. Над ним не появляются кнопки.

Другой подход, который я попытался добавить в верхнюю часть ListView. Однако, когда я это сделал, он успешно переместился вниз, однако, если я добавил что-либо выше, он переместил ListView. Независимо от того, что я делаю, кажется, что я не могу поместить несколько кнопок над ListView, когда я использовал ListActivity.

Спасибо заранее.

synic, я попробовал ваше предложение раньше. Я попробовал это снова ради здравого смысла, и кнопка не отображалась. Ниже представлен файл макета для активности и код, который я реализовал в oncreate().

//Моя listactivity Я пытаюсь добавить заголовок в

public class AuditActivity extends ListActivity {

    Budget budget;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        Cursor test;
        super.onCreate(savedInstanceState);
        setContentView(R.layout.audit);
        ListView lv = getListView();
        LayoutInflater infalter = getLayoutInflater();
        ViewGroup header = (ViewGroup) infalter.inflate(R.layout.header, lv, false);
        lv.addHeaderView(header);
        budget = new Budget(this);
        /*
        try {
            test = budget.getTransactions();
            showEvents(test);
        } finally {

        }
        */
//      switchTabSpecial();
    }

Layout.xml для активности:

<?xml version="1.0" encoding="utf-8"?>

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent" android:layout_height="fill_parent">
    <ListView android:id="@android:id/list" android:layout_width="wrap_content"
        android:layout_height="wrap_content" />
    <TextView android:id="@android:id/empty" android:layout_width="wrap_content"
        android:layout_height="wrap_content" android:text="@string/empty" />
</LinearLayout>
4b9b3361

Ответ 1

findViewById() работает только для поиска подзонов объекта View. Он не будет работать с идентификатором макета.

Вам нужно будет использовать макетный надувной элемент для преобразования xml в соответствующие компоненты View. Что-то вроде этого:

ListView lv = getListView();
LayoutInflater inflater = getLayoutInflater();
View header = inflater.inflate(R.layout.header, lv, false);
lv.addHeaderView(header, null, false);

Я не уверен, почему ваш код не просто выбросил ошибку. findViewById(), вероятно, просто возвращал null, поэтому в ваш список не добавлялся заголовок.

Ответ 2

Вот самое простое решение:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
 xmlns:android="http://schemas.android.com/apk/res/android"
 android:orientation="vertical"
 android:layout_width="fill_parent"
 android:layout_height="fill_parent"
 android:background="@color/background">
 <include layout="@layout/actionbar"/>
   <ListView
    android:id="@+id/tasklist_TaskListView"
    android:layout_width="fill_parent"
    android:layout_height="0dip"
    android:layout_weight="1"
    android:textColor="@color/baseFont"/>
   <include layout="@layout/bottombar"/>
</LinearLayout>

или

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
 xmlns:android="http://schemas.android.com/apk/res/android"
 android:orientation="vertical"
 android:layout_width="fill_parent"
 android:layout_height="fill_parent"
 android:background="@color/background">
   <Button 
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"/>
   <ListView
    android:id="@+id/tasklist_TaskListView"
    android:layout_width="fill_parent"
    android:layout_height="0dip"
    android:layout_weight="1"
    android:textColor="@color/baseFont"/>
   <Button 
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"/>

</LinearLayout>

вместо кнопки вы можете добавить еще один горизонтальный линейный макет

Ответ 3

После некоторых исследований мне удалось выяснить, что смешивание TableLayout и LinearLayout в моем XML-документе ListActivity мне удалось добавить заголовок в документ. Ниже мой XML-документ, если кому-то интересно его видеть. Хотя синаксический подход, вероятно, правильный подход после работы с его решением на некоторое время, я не смог заставить его функционировать так, как я этого хотел.

AuditTab.java

public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.audittab);
        getListView().setEmptyView(findViewById(R.id.empty));
}

audittab.xml

<?xml version="1.0" encoding="utf-8"?>
<TableLayout 
    android:layout_width="fill_parent"
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_height="fill_parent">
    <TableRow 
        android:layout_width="fill_parent"
        android:layout_height="fill_parent" 
        android:layout_gravity="center_horizontal">
        <LinearLayout 
            xmlns:android="http://schemas.android.com/apk/res/android"
            android:layout_width="fill_parent" 
            android:layout_height="fill_parent"
            android:orientation="horizontal" 
            android:layout_weight="1">
            <Button 
                android:id="@+id/btnFromDate" 
                android:layout_width="fill_parent"
                android:layout_height="wrap_content" 
                android:text=""
                android:layout_weight="1" />
            <Button 
                android:id="@+id/btnToDate" 
                android:layout_width="fill_parent"
                android:layout_height="wrap_content" 
                android:text=""
                android:layout_toRightOf="@+id/btnFromDate"
                android:layout_weight="1" />
            <Button 
                android:id="@+id/btnQuery" 
                android:layout_width="fill_parent"
                android:layout_height="wrap_content" 
                android:text="Query"
                android:layout_toRightOf="@+id/btnToDate"
                android:layout_weight="1" />

        </LinearLayout>
    </TableRow>
    <TableRow 
        android:layout_width="fill_parent"
        android:layout_height="fill_parent" 
        android:layout_gravity="center_horizontal">
        <LinearLayout 
            android:layout_width="fill_parent"
            android:layout_height="fill_parent">
            <ListView 
                android:id="@android:id/list"
                android:layout_width="300dip" 
                android:layout_height="330dip"
                android:scrollbars="none" />
            <TextView 
                android:id="@+id/empty"
                android:layout_width="wrap_content" 
                android:layout_height="wrap_content"
                android:paddingTop="10dip"
                android:text="- Please select a date range and press query." />
        </LinearLayout>
    </TableRow>
</TableLayout>

AuditItem.xml

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout 
        xmlns:android="http://schemas.android.com/apk/res/android"
        android:layout_width="fill_parent" 
        android:orientation="horizontal" 
        android:padding="10sp">
    <TextView 
        android:id="@+id/transactionDateLabel" 
        android:layout_width="wrap_content" 
        android:layout_height="wrap_content" 
        android:text="Date: " />
    <TextView 
        android:id="@+id/transactionDate" 
        android:layout_width="wrap_content"
        android:layout_height="wrap_content" 
        android:layout_toRightOf="@id/transactionDateLabel" />
    <TextView 
        android:id="@+id/transactionTypeLabel" 
        android:layout_below="@id/transactionDate" 
        android:layout_width="wrap_content" 
        android:layout_height="wrap_content" 
        android:text="Type: " />
    <TextView 
        android:id="@+id/transactionType" 
        android:layout_width="wrap_content"
        android:layout_height="wrap_content" 
        android:layout_marginLeft="10dip" 
        android:layout_below="@id/transactionDate"
        android:layout_toRightOf="@id/transactionTypeLabel" />

    <TextView 
        android:id="@+id/transactionAmountLabel" 
        android:layout_width="wrap_content" 
        android:layout_height="wrap_content" 
        android:layout_marginLeft="10dip"
        android:text="Amount: " 
        android:layout_below="@id/transactionDate"
        android:layout_toRightOf="@id/transactionType" />
    <TextView 
        android:id="@+id/transactionAmount" 
        android:layout_width="wrap_content"
        android:layout_height="wrap_content" 
        android:layout_below="@id/transactionDate"
        android:layout_toRightOf="@id/transactionAmountLabel" />
    <TextView 
        android:id="@+id/transactionCategoryLabel" 
        android:layout_width="wrap_content" 
        android:layout_height="wrap_content" 
        android:text="Category: " 
        android:layout_below="@id/transactionAmountLabel" />
    <TextView 
        android:id="@+id/transactionCategory" 
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_below="@id/transactionAmountLabel" 
        android:layout_toRightOf="@id/transactionCategoryLabel"
        />
    <TextView 
        android:id="@+id/transactionToAccountLabel" 
        android:layout_width="wrap_content" 
        android:layout_height="wrap_content" 
        android:text="To Account: " 
        android:layout_below="@id/transactionCategoryLabel" />
    <TextView
        android:id="@+id/transactionToAccount"
        android:layout_width="wrap_content" 
        android:layout_height="wrap_content"
        android:layout_below="@+id/transactionCategoryLabel"
        android:layout_toRightOf="@id/transactionToAccountLabel" />
    <TextView 
        android:id="@+id/transactionFromAccountLabel" 
        android:layout_width="wrap_content" 
        android:layout_height="wrap_content" 
        android:text="From Account: " 
        android:layout_below="@id/transactionToAccountLabel" />
    <TextView
        android:id="@+id/transactionFromAccount"
        android:layout_width="wrap_content" 
        android:layout_height="wrap_content"
        android:layout_below="@id/transactionToAccountLabel"
        android:layout_toRightOf="@id/transactionFromAccountLabel" />
    <TextView 
        android:id="@+id/transactionNoteLabel" 
        android:layout_width="wrap_content" 
        android:layout_height="wrap_content" 
        android:text="Note: " 
        android:layout_below="@id/transactionFromAccountLabel" />
    <TextView 
        android:id="@+id/transactionNote" 
        android:layout_width="wrap_content"
        android:layout_height="wrap_content" 
        android:layout_below="@id/transactionFromAccountLabel" 
        android:layout_toRightOf="@id/transactionNoteLabel" />
    <Button 
        android:id="@+id/editTransactionBtn" 
        android:layout_width="wrap_content"
        android:layout_height="40sp" 
        android:visibility="gone" 
        android:text="Edit"
        android:layout_below="@id/transactionNoteLabel"/>
    <Button 
        android:id="@+id/deleteTransactionBtn" 
        android:layout_width="wrap_content"
        android:layout_height="40sp" 
        android:text="Delete" 
        android:layout_below="@+id/transactionNoteLabel" 
        android:visibility="gone" 
        android:layout_toRightOf="@+id/editTransactionBtn" 
        android:ellipsize="end"/>
</RelativeLayout>

Ответ 4

Ответ ListView, приведенный выше, полезен, но прокручивает список и не сохраняет заголовок графики вверху. Лучшее решение, которое я нашел, - установить пользовательский заголовок для активности. Вот как выглядит мой конструктор:

public void onCreate(Bundle savedInstanceState) {
    requestWindowFeature(Window.FEATURE_CUSTOM_TITLE);
    setContentView(R.layout.your_listview_layout);
    getWindow().setFeatureInt(Window.FEATURE_CUSTOM_TITLE, R.layout.your_header);
    ...

Где your_listview_layout.xml настраивает ListView, а your_header.xml содержит любой настраиваемый макет заголовка, который вам нравится. Просто обратите внимание, что три строки выше должны быть вызваны именно в том порядке, чтобы не вызывать проблемы во время выполнения.

Учебник, который помог мне, был http://www.londatiga.net/it/how-to-create-custom-window-title-in-android/, и вы можете найти много связанных страниц в "Переполнение стека", выполнив поиск термина "setFeatureInt"

Ответ 5

Добавление статического заголовка легко, просто создайте отдельный относительный вид, для которого атрибут alignParentTop (или нижний, правый или левый) установлен в true.