sábado, 16 de junio de 2012

Personaliza tus listas (ListView)

En la mayoría de las aplicaciones se requiere de crear listas personalizadas. Android ofrece diferentes layouts que podemos usar, pero cuando estos no son suficientes para nuestro gusto tenemos que implementar nuestro propio layout y BaseAdapter. En este post vamos a ver un ejemplo de ello:

Contiene la lista que se muestra al usuario. Vista principal de la Activity.
res/layout/main.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" >
    <ListView
        android:id="@+id/listView"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"/>
</LinearLayout>

Contiene el formato que tendrá cada elemento de la lista. Usado la clase CustomAdapter.
res/layout/custom_list.xml
 <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:orientation="horizontal" >
    <LinearLayout
        android:id="@+id/linearLayout_1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentRight="true"
        android:layout_marginRight="10dip"
        android:orientation="horizontal"
        android:paddingTop="7dip" >
        <TextView
            android:id="@+id/textView_date"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content" >
        </TextView>
    </LinearLayout>
    <TextView
        android:id="@+id/textView_title"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_below="@+id/linearLayout_1"
        android:layout_marginLeft="5dip"
        android:layout_marginTop="5dip"
        android:textSize="15sp"
        android:textStyle="bold" >
    </TextView>
    <TextView
        android:id="@+id/textView_description"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_below="@+id/textView_title"
        android:layout_marginLeft="12dip"
        android:layout_marginTop="5dip"
        android:textSize="12sp"
        android:textStyle="italic" >
    </TextView>
</RelativeLayout>

Esta clase sirve para rellenar los datos de cada elemento de la lista.
src/CustomAdapter.java
public class CustomAdapter extends BaseAdapter {

    private Activity mActivityAct;
    private LayoutInflater mInflater;
    private ArrayList<Notice> mLItems;

    public CustomAdapter(Activity a, ArrayList<Notice> it) {
        mActivityAct = a;
        mLItems = it;
        mInflater = (LayoutInflater) mActivityAct
                .getSystemService(Context.LAYOUT_INFLATER_SERVICE);
    }

    public static class VistaH {
        public TextView date;
        public TextView title;
        public TextView description;
    }

    @Override
    public int getCount() {
        return mLItems.size();
    }

    @Override
    public Object getItem(int position) {
        return position;
    }

    @Override
    public long getItemId(int position) {
        return position;
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        View vi = convertView;
        VistaH vh = null;

        if (vi == null) {
            vi = mInflater.inflate(R.layout.custom_list, null);
            vh = new VistaH();
            vh.date = (TextView) vi.findViewById(R.id.textView_date);
            vh.title = (TextView) vi.findViewById(R.id.textView_title);
            vh.description = (TextView) vi
                    .findViewById(R.id.textView_description);
            vi.setTag(vh);
        }

        vh = (VistaH) vi.getTag();

        Notice notice = mLItems.get(position);
        vh.date.setText(notice.getDate());
        vh.title.setText(notice.getTitle());
        vh.description.setText(notice.getDescription());

        return vi;
    }

    @Override
    public void unregisterDataSetObserver(DataSetObserver observer) {
        if (observer != null) {
            super.unregisterDataSetObserver(observer);
        }
    }
}

Vista principal. Contiene la lista. Modifica el adapter del listView por el CustomAdapter. Le pasamos el contexto y los datos (en este caso Notice (elemento del modelo)).
res/MyActivity.java
public class MyActivity extends Activity {

    private ListView mListView;
    private ArrayList<Notice> mList = new ArrayList<Notice>();
    private Activity mActivity;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        mListView = (ListView) findViewById(R.id.listView);
        mActivity = this;

        getDataFromWebService();

        CustomAdapter actualitatAdapter = new CustomAdapter(this, mList);
        mListView.setAdapter(actualitatAdapter);
        mListView.setOnItemClickListener(new OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> av, View view, int index,
                    long arg3) {
                Toast.makeText(mActivity,
                        "My title is: " + mList.get(index).getTitle(),
                        Toast.LENGTH_LONG).show();
            }
        });

    }

    private void getDataFromWebService() {

        // p.e: get Notices from rss
        Notice n = new Notice("16/06/2012", "Notice 1",
                "This is the description from notice 1");
        mList.add(n);
        n = new Notice("14/06/2012", "Notice 2",
                "This is the description from notice 2");
        mList.add(n);
        n = new Notice("13/06/2012", "Notice 3",
                "This is the description from notice 3");
        mList.add(n);
        n = new Notice("13/06/2012", "Notice 4",
                "This is the description from notice 4");
        mList.add(n);
        n = new Notice("12/06/2012", "Notice 5",
                "This is the description from notice 5");
        mList.add(n);
        n = new Notice("11/06/2012", "Notice 6",
                "This is the description from notice 6");
        mList.add(n);
        n = new Notice("09/06/2012", "Notice 7",
                "This is the description from notice 7");
        mList.add(n);
        n = new Notice("09/06/2012", "Notice 8",
                "This is the description from notice 8");
        mList.add(n);
        n = new Notice("03/06/2012", "Notice 9",
                "This is the description from notice 9");
        mList.add(n);

    }
}


Elemento del modelo. Contiene los atributos que se muestran en la lista.
res/Notice.java
public class Notice {
    private String date;
    private String title;
    private String description;

    public Notice(String date, String title, String description) {
        this.date = date;
        this.title = title;
        this.description = description;
    }

    public String getDate() {
        return date;
    }

    public void setDate(String date) {
        this.date = date;
    }

    public String getTitle() {
        return title;
    }

    public void setTitle(String title) {
        this.title = title;
    }

    public String getDescription() {
        return description;
    }

    public void setDescription(String description) {
        this.description = description;
    }
}

Si ejecutamos el proyecto se nos mostraría la siguiente imagen:

 

It works!

Roger Sala,

No hay comentarios:

Publicar un comentario