Inserting TextView into a ListView

1

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

Follow the base 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 methods I found were returning the convertView instead of the proposed textview in the sample.

I'm a little lost.

    
asked by anonymous 18.07.2015 / 21:57

1 answer

0

You first need to create a Layout that will represent each of the ListView rows. In this case it will be a LinearLayout with a TextView inside.

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 Adapter% method is called whenever a new line in the list needs to be displayed, if getView() is convertView use LayoutInflater to convert the layout into a View object and assign it to it.

Use the null method to get a reference to TextView , put the value corresponding to that line in it, return it to findViewById() .

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 to do it.

    
18.07.2015 / 22:23