Inserting Textview into a Listview

Asked

Viewed 415 times

1

I have a problem. I need to insert a textview inside a listview.

Follows the basic method

class MyKickAssAdapter extends BaseAdapter {
    LayoutInflater mInflater = LayoutInflater.from(getContext());
    //...

    public View getView(int position, View convertView, ViewGroup parent) {
        TextView tv;

        // fazer a inserção aqui

        tv.setText("Hello Ideais!");
        return tv;
    }
}

All the methods I found were returning to convertView instead of the proposed textview in the sample.

I’m a little lost.

1 answer

0


First you have to create a Layout which will represent each of the Listview. In your case it will be a Linearlayout with a Textview within.

res/layout/item_list.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content" >

    <TextView
        android:id="@+id/text"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
    </TextView>

</LinearLayout>  

The method getView() of Adapter is called whenever a new line in the list needs to be displayed, if the convertView for null use the Layoutinflater to convert the layout in an object View and attribute it to her.

Use the method findViewById() to obtain a reference to Textview, put in it the value corresponding to that line, return to convertView.

public class MyKickAssAdapter extends BaseAdapter {
    private Context context;
    private ArrayList<String> oMeuArray;
    private LayoutInflater mInflater;

    MyKickAssAdapter(Context context, ArrayList oMeuArray){
        mInflater = LayoutInflater.from(context);
        this.context = context;
        this.oMeuArray = oMeuArray;
    }
    //...

    public View getView(int position, View convertView, ViewGroup parent) {
        TextView tv;

        if(convertView == null){
            convertView = mInflater.inflate(R.layout.item_lista, parent, false);
        }

        tv = (TextView)convertView.findViewById(R.id.text);
        tv.setText(oSeuArray.get(i));
        //Se cada linha tivesse mais views eram actualizadas aqui
        ...
        ...
        return convertView;
    }
}

This is the basics, if you want to see here a more correct/efficient way of doing.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.