miércoles, 28 de marzo de 2012

Android ListActivity con adaptador

Un paso más es tener un adaptador, que más adelante se puede adaptar para incluir en la lista cualquier objeto, como un botón, una imagen.
Partiendo del proyecto anterior, véase este enlace, hay que modificar en main.xml el identificador del ListView, ha de quedar con android:id="@android:id/list". Sirve para la Activity que cambiaremos a ListActivity.
El elemento a utilizar en el ListView por sencillez va a ser un TextView, hay que crear otro xml, lo he llamado element.xml y es este:


<?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" >
    
<TextView 
    android:id="@+id/tvelement"
    android:layout_height="fill_parent"
    android:layout_width="fill_parent"
    android:text="item"/>
</LinearLayout>

Voy a necesitar una clase muy sencilla para representar a mi elemento, creamos la nueva clase Element:


public class Element {


    private String name;


    public Element(String name) {
        super();
        this.name = name;
    }


    public String getName() {
        return name;
    }


    public void setName(String name) {
        this.name = name;
    }
}

Y la clase de prueba MilistviewActivity queda así:



public class MilistviewActivity extends ListActivity {
    private ElementAdapter myElementAdapter;
private ArrayList<Element> elements = null;
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
      //Assign objects
        final Button mybutton = (Button) findViewById(R.id.addbutton);
        final EditText myEdittext = (EditText) findViewById(R.id.edittext);
        
      //Use of ElementAdapter
        elements = new ArrayList<Element>();
        myElementAdapter = new ElementAdapter(this, R.layout.element, elements);
        setListAdapter(myElementAdapter);
        
        mybutton.setOnClickListener(new OnClickListener() {
        public void onClick(View v) {
      myElementAdapter.add(new Element(myEdittext.getText().toString()));
        myElementAdapter.notifyDataSetChanged();
  }
 });   
        
    }
    
    //class ElementAdapter
    public class ElementAdapter extends ArrayAdapter<Element> {
        private ArrayList<Element> items;
        private ViewHolder holder;
        class ViewHolder {
            TextView name;
        }
        
        public ElementAdapter(Context context, int textViewResourceId, ArrayList<Element> items) {
            super(context, textViewResourceId, items);
            this.items = items;
        }
        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            View v = convertView;
            if(v == null) {
                LayoutInflater vi = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
                v = vi.inflate(R.layout.element, null);
                holder = new ViewHolder();
                holder.name = (TextView) v.findViewById(R.id.tvelement);
                v.setTag(holder);
            } else {
                holder = (ViewHolder) v.getTag();
            }
            Element listViewItem = items.get(position);
            
            holder.name.setText(listViewItem.getName());
            
            return v;
        }
    }



El aspecto es parecido:
Sin embargo, se pueden añadir otros objetos, para ello se cambia el objeto element por otro que puede estar compuesto de texto+botón, o texto+imagen; modificando por supuesto el adapter para que sea ArrayAdapter<de_otro_elemento>.

La fuente principal ha sido esta.

Un cordial

No hay comentarios:

Publicar un comentario