Android: Как добавить кнопку в представление списка сверху, используя базовый адаптер - PullRequest
0 голосов
/ 24 мая 2011

В моем приложении я хочу добавить кнопку в список сверху.В этом случае он показывает кнопку в каждом элементе списка, а не сверху.Как показывать только сверху

sex.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"
  android:orientation="Vertical"

 >

<Button
        android:id="@+id/b1
        android:layout_width="wrap_content"
        android:layout_height="wrap_content" />


<LinearLayout
  android:layout_width="fill_parent"
  android:layout_height="fill_parent"
  android:orientation="horizontal"

 >

     <TextView android:id="@+id/text"
        android:layout_gravity="center_vertical"
        android:layout_width="0dip"
        android:layout_weight="1.0"
        android:layout_height="wrap_content" />


        <CheckBox android:id="@+id/checkbox"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"

        />     

</LinearLayout>
</LinearLayout>

Egender.java

package com.Elgifto;

import android.app.ListActivity;
import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.ListView;
import android.widget.RadioButton;
import android.widget.TextView;

public class Egender extends ListActivity {

    private static class EfficientAdapter extends BaseAdapter {
        private LayoutInflater mInflater;

        public EfficientAdapter(Context context) {
            // Cache the LayoutInflate to avoid asking for a new one each time.
            mInflater = LayoutInflater.from(context);           
        }

        /**
         * The number of items in the list is determined by the number of speeches
         * in our array.
         *
         * @see android.widget.ListAdapter#getCount()
         */
        public int getCount() {
            return GENDER.length;
        }

        /**
         * Since the data comes from an array, just returning the index is
         * sufficent to get at the data. If we were using a more complex data
         * structure, we would return whatever object represents one row in the
         * list.
         *
         * @see android.widget.ListAdapter#getItem(int)
         */
        public Object getItem(int position) {
            return position;
        }

        /**
         * Use the array index as a unique id.
         *
         * @see android.widget.ListAdapter#getItemId(int)
         */
        public long getItemId(int position) {
            return position;
        }

        /**
         * Make a view to hold each row.
         *
         * @see android.widget.ListAdapter#getView(int, android.view.View,
         *      android.view.ViewGroup)
         */
        public View getView(int position, View convertView, ViewGroup parent) {
            // A ViewHolder keeps references to children views to avoid unneccessary calls
            // to findViewById() on each row.
            ViewHolder holder;

            // When convertView is not null, we can reuse it directly, there is no need
            // to reinflate it. We only inflate a new View when the convertView supplied
            // by ListView is null.
            if (convertView == null) {
                convertView = mInflater.inflate(R.layout.gender, null);

                // Creates a ViewHolder and store references to the two children views
                // we want to bind data to.
                holder = new ViewHolder();
                holder.text = (TextView) convertView.findViewById(R.id.text);
                holder.cb=(CheckBox) convertView.findViewById(R.id.checkbox);


                convertView.setTag(holder);
            } else {
                // Get the ViewHolder back to get fast access to the TextView
                // and the ImageView.
                holder = (ViewHolder) convertView.getTag();
            }

            // Bind the data efficiently with the holder.
            holder.text.setText(GENDER[position]);
            //holder.text.setTextColor(Color.BLACK);
            if(holder.cb.isChecked())
            {
                holder.cb.setChecked(false);
                String st=GENDER[position];
                System.out.println("String:"+st);
            }

                 return convertView;
        }

        static class ViewHolder {

            TextView text;
            CheckBox cb;
        }
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        setListAdapter(new EfficientAdapter(this));
    }

      private static final String[] GENDER = new String[] {
       "Male","Female"
    };
}

спасибо

Ответы [ 2 ]

0 голосов
/ 02 декабря 2013

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

Button btn=new Button(this);
list.addHeaderView(btn);

это сделает первый элемент вашего просмотра списка еще сильнее

Вы также можете сделать его недоступным для выбора с помощью

list.addHeaderView(vbtn, null, false);

И отправил onItemClickListener.

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

Если я не ошибаюсь, вы используете гендер.xml в качестве макета для каждой строки / элемента в ListView.Итак, вы, вероятно, захотите удалить объявление Button из макета sex.xml.

Если вы хотите, чтобы Button фиксировалась над ListView, то вы, вероятно, захотите отредактировать макет, который также объявляет ListViewобъявите Button, предполагая, что у вас есть такой макет xml.

Например, макет xml с ListView может выглядеть примерно так:

<LinearLayout orientation="horizontal">
    <Button 
        id="my_button"
        width="wrap_content"
        height="wrap_content"
        layout_gravity="center"
        text="my button" />
    <ListView 
        id="my_listview"
        width="fill_parent"
        height="0dip"
        weight="1" />
</LinearLayout>
(Примечание. Этот макет xmlне является полным и пропускает фрагменты, такие как объявление xmlns. Для более полного примера взгляните на Прокрутка текста над кнопками, кнопки с фиксированным основанием .)
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...