I have to create a list whose list items have 2 lines of text. I started building a custom list item, but then I discovered the TwoLineListItem component. I wrote this code:
pageFilterResultView=new TwoLineListItem(containerActivity);
pageFilterResultView.getText1().setText("Test");
However, getText1 returns null, and the second line throws a NullPointerException. So I thought I need to use an inflated layout instead of a constructor. The TwoLineListItem documentation specifies I can use the android.R.layout.two_line_list_item resource for the layout, so I changed the code to:
LayoutInflater inflater=(LayoutInflater)containerActivity.
getSystemService(Context.LAYOUT_INFLATER_SERVICE);
pageFilterResultView=(TwoLineListItem)inflater.inflate(android.R.
layout.two_line_list_item,null);
pageFilterResultView.getText1().setText("Test");
However, this throws a ClassCastException because the layout is actually a LinearLayout. TwoLineListItem inherits from RelativeLayout, so I can’t even cast the layout to a higher class in the hierarchy.
So the question is: How do I use TwoLineListItem correctly? Do I have to create my own custom layout for it? If so, what’s the point of this component if I still have to do all the work of creating a list item by myself?
The
TwoLineListItemwidget is a facade over twoTextViewsthat have to be provided by you. To use theTwoLineListItemin aListView‘s row you’ll need a row layout where you have theTwoLineListItemwidget with two(at least)TextViewchildren with specific ids(android.R.id.text1andandroid.R.id.text2). Something like this:Then you can use it in the
getView()method like you did:Of course you have the possibility of using an included layout file as the child of the
TwoLineListItem(as long as you have the twoTextViewswith the required ids):but this just increases the layout depth and should be avoided.
Judging by the fact that you can’t use this widget programmatically, I don’t see the need for this component either.