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

viernes, 23 de marzo de 2012

Alimentar ListView

No pretendo enseñar cómo se programa en Android,  pero este post me servirá de referencia.
Voy a contar cómo se alimenta un ListView desde un campo que se teclee, algo como esto:


Se trata de alimentar el ListView según se pulsa el botón.
Primero se crea el proyecto en Eclipse, si no se sabe, con Google es fácil encontrarlo. A mi proyecto lo he llamado Milistview y el XML main es así:


<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="vertical" >
    <EditText
        android:id="@+id/edittext"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textColor="#0000ff" />
    <Button
        android:id="@+id/addbutton"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Add" />
<ListView
        android:id="@+id/l_newlist"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"
        android:textColor="#00ffff" 
         />
</LinearLayout>


La clase queda de esta manera:


public class MilistviewActivity extends Activity {
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        
        //Assign objects
        final ListView myListView = (ListView) findViewById(R.id.l_newlist);
        final EditText myEdittext = (EditText) findViewById(R.id.edittext);
        final Button mybutton = (Button) findViewById(R.id.addbutton);
        final ArrayList<String> elements = new ArrayList<String>();
       
        //the adapter
        final ArrayAdapter<String> myadapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, elements);
        myListView.setAdapter(myadapter);
        // the listener
        mybutton.setOnClickListener(new OnClickListener() {

@Override
public void onClick(View v) {
elements.add(myEdittext.getText().toString());
myadapter.notifyDataSetChanged();
}
});
        
    }
} 




Y sigue funcionando:


Cordiales.