Как показать кнопку в конце списка Android ListView - PullRequest
41 голосов
/ 05 марта 2010

Я хочу показать кнопку в конце списка Android.Как мне этого добиться?

Я не хочу привязывать его к основанию активности, используя alignparentbottom="true".Использование layout_below также не работает для меня.

Мой текущий XML:

<?xml version="1.0" encoding="UTF-8"?>
<RelativeLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="horizontal"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:background="@drawable/main_bg">

    <LinearLayout
        xmlns:android="http://schemas.android.com/apk/res/android"
        android:orientation="vertical"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content">

        <ListView
            android:id="@+id/android:list"
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:drawSelectorOnTop="false"
            android:cacheColorHint="#ff6a00"
            android:divider="#ff8f40"
            android:dividerHeight="1px" />

    </LinearLayout>

    <RelativeLayout
        xmlns:android="http://schemas.android.com/apk/res/android"
        android:layout_width="fill_parent"
            android:layout_height="50sp"
        android:background="#676767"
        android:orientation="vertical">

        <Button
            android:layout_width="100px"
            android:layout_height="wrap_content"
            android:id="@+id/btnGetMoreResults"
            android:layout_marginLeft="10px"
            android:text="Get more" />

    </RelativeLayout>

</RelativeLayout>

Ответы [ 9 ]

74 голосов
/ 05 марта 2010

Вы можете использовать ListView # addFooterView () , чтобы добавить View внизу ListView.

34 голосов
/ 10 апреля 2012

Мне нравится эта фиксированная кнопка в нижней части экрана

   <RelativeLayout
    android:id="@+id/relativeLayout"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <ListView
        android:id="@+id/listView"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"
        android:layout_above="@+id/btn_New" >
    </ListView>

    <Button
        android:id="@+id/btn_New"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerHorizontal="true"
        android:layout_centerVertical="true"
        android:layout_marginBottom="20dp"
        android:text="@string/New"
        android:width="170dp"
        android:layout_alignParentBottom="true" />
</RelativeLayout>

если вы используете linearLayout, присвойте android: layout_weight = "1" представлению списка и не назначайте вес кнопке, это работает

15 голосов
/ 28 июня 2011

Вы можете сделать что-то вроде этого:

final Button btnAddMore = new Button(this);
btnAddMore.setText(R.string.art_btn_moreIssues);
exArticlesList = (ExpandableListView) this.findViewById(R.id.art_list_exlist);
exArticlesList.addFooterView(btnAddMore);
7 голосов
/ 05 марта 2010

1 Если вы хотите добавить Button в качестве последнего элемента представления списка

Вы должны создать пользовательский ListAdapter для вашего ListView, который создаст представление сКнопка в методе getView.Вы должны решить, как вернуть свое пользовательское представление для последнего элемента, вы можете жестко закодировать его (вернуть количество элементов +1 в методе getCount и вернуть пользовательское представление в getView, когда position> count элемента), или вы можете добавить элемент в структуру, которой вы будетеберу данные из (Массив, Курсор и т. д.) и проверяю, имеет ли поле элемента определенное значение

2 Если вы хотите добавить элемент ниже представления списка

Вы должны использоватьandroid: атрибут layout_width и сделать ListView и «пустой» TextView (вы должны использовать его, чтобы показать пользователям, что список пуст и представление View завершено) layout_weight больше, чем кнопки layout_weight

Проверьте, как это делается в поиске Transdroids.1015 *http://code.google.com/p/transdroid/source/browse/trunk/res/layout/search.xml

6 голосов
/ 11 марта 2014

Используйте просмотр нижнего колонтитула для просмотра списка.

list_layout.xml:

<LinearLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content">

    <ListView
        android:id="@+id/list"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:drawSelectorOnTop="false"
        android:cacheColorHint="#ff6a00"
        android:divider="#ff8f40"
        android:dividerHeight="1px" />

</LinearLayout>

footerview.xml:

<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
>
    <Button
        android:layout_width="100px"
        android:layout_height="wrap_content"
        android:id="@+id/btnGetMoreResults"
        android:layout_marginLeft="10px"
        android:text="Get more" />
</FrameLayout>

и в Activity.java

    list=(ListView)findViewById(R.id.list);

    FrameLayout footerLayout = (FrameLayout) getLayoutInflater().inflate(R.layout.footerview,null);
    btnPostYourEnquiry = (Button) footerLayout.findViewById(R.id.btnGetMoreResults);

    list.addFooterView(footerLayout);
4 голосов
/ 16 января 2015

Просто укажите "layout_weight = 1" ListView.

Пример:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
              android:orientation="vertical"
              android:layout_width="match_parent"
              android:layout_height="match_parent">
    <ListView
        android:id="@+id/android:list"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:drawSelectorOnTop="false"
        android:cacheColorHint="#ff6a00"
        android:divider="#ff8f40"
        android:layout_weight="1"
        android:dividerHeight="1px" />
    <Button
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_gravity="bottom"
        android:layout_marginLeft="10dp"
        android:layout_marginRight="10dp"
        android:background="#ff8f40"
        android:padding="20dp"
        android:text="Click"
        android:textColor="#FFFFFF"
        android:textSize="22sp"
        />
</LinearLayout>
3 голосов
/ 18 мая 2014

Сначала я пришел сюда в поисках ответа, но нашел его где-то еще ...

Это действительно просто, вам просто нужно поместить вес 1 в список внутри линейного макета, другие текстовые представления / кнопки / и т. Д. Не должны иметь никакого значения веса.

Вот пример: https://bitbucket.org/generalplus/android_development/src/5a892efb0551/samples/ApiDemos/res/layout/linear_layout_9.xml

0 голосов
/ 23 мая 2011

Ну ... детали реализации не так просты, если вы хотите создать плавную кнопку «добавить еще» в конце списка. Итак, вот код:

myArrayAdapter = new ArrayAdapter<Show>(this, android.R.layout.simple_list_item_1, myList) {

     @Override
     public View getView(int position, View convertView, ViewGroup parent) {

        if( position >= super.getCount()  )
            return buttonMore ;

        MyNormalView view = null; 
        if (convertView == null || convertView instanceof Button )
            view = new MyNormalView(getContext());
        else
            view = (MyNormalView) convertView;

        //customize view here with data
        return view;
    }

    @Override
    public int getCount() {
       return super.getCount()+1;
    }//met
};
0 голосов
/ 05 марта 2010

Конечно, вы можете использовать собственный адаптер и указать элемент нижнего колонтитула.Но, возможно, вам также может не понравиться поместить его внизу ScrollView и растянуть ListView по вертикали до содержимого:

<?xml version="1.0" encoding="UTF-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="horizontal"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:background="@drawable/main_bg">

  <ScrollView
      android:layout_height="fill_parent"
      android:layout_width="fill_parent">

    <LinearLayout 
        android:orientation="vertical"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
            >

      <ListView android:id="@+id/android:list"
          android:layout_width="fill_parent" 
          android:layout_height="wrap_content"
          android:drawSelectorOnTop="false" 
          android:cacheColorHint="#ff6a00"
          android:divider="#ff8f40"
          android:dividerHeight="1px"
          />

      <RelativeLayout 
          android:layout_width="fill_parent"
          android:layout_height="50sp"
          android:background="#676767"
          android:orientation="vertical">

        <Button android:layout_width="100px"
            android:layout_height="wrap_content"
            android:id="@+id/btnGetMoreResults"
            android:layout_marginLeft="10px"
            android:text="Get more" />

      </RelativeLayout>

    </LinearLayout>

  </ScrollView>

</RelativeLayout>
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...