ListActivity TwoLineListItem Alternative

John Roberts picture John Roberts · Nov 27, 2012 · Viewed 7.6k times · Source

I notice that TwoLineListItem is deprecated as of API 17. What is the alternative to this if I am setting up a ListActivity adapter as follows?:

ArrayAdapter<File> adapter = new ArrayAdapter<File>(this,android.R.layout.simple_list_item_2,filesArrayList){
            @Override
            public View getView(int position, View convertView, ViewGroup parent){
                final TwoLineListItem row;
                if(convertView == null){
                    LayoutInflater inflater = (LayoutInflater)getApplicationContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
                    row = (TwoLineListItem)inflater.inflate(android.R.layout.simple_list_item_2, null);
                }else{
                    row = (TwoLineListItem)convertView;
                }
                row.getText1().setText(filesArrayList.get(position).getTitle());
                row.getText2().setText2(filesArrayList.get(position).getDescription());
                return row;
            }

        };

Answer

Sam picture Sam · Nov 27, 2012

Simply cut and paste the TwoLineListItem source code into a layout of your own:

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:orientation="vertical">

    <TextView android:id="@+id/text1"
        android:textSize="16sp"
        android:textStyle="bold"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"/>

    <TextView android:id="@+id/text2"
        android:textSize="16sp"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"/>

</LinearLayout>

(Notice I changed the ids for consistency.)

Now use a ViewHolder that keeps references to both TextViews:

public View getView(int position, View convertView, ViewGroup parent){
    ViewHolder holder;
    if(convertView == null){
        // You should fetch the LayoutInflater once in your constructor
        LayoutInflater inflater = (LayoutInflater)getApplicationContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        convertView = inflater.inflate(R.layout.list_item_2, null);

        // Initialize ViewHolder here
    }else{
        holder = (ViewHolder) convertView.getTag();
    }

    File file = filesArrayList.get(position);
    holder.text1.setText(file.getTitle());
    holder.text2.setText2(file.getDescription());
    return convertView;
}