I’m trying to write a custom adapter to adapt a simple class into a ListView. The class is for SMS messages and it contains simple fields like body, sender address, etc. Below, see my adapter layout:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent" >
<ImageView
android:id="@+id/imgContactPhoto"
android:contentDescription="Contact photo"
android:layout_width="90sp"
android:layout_height="90sp" />
<TextView
android:id="@+id/lblMsg"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_toRightOf="@id/imgContactPhoto"
android:paddingLeft="10sp" />
</RelativeLayout>
And my custom adapter class:
public class SmsListAdapter extends ArrayAdapter{
private int resource;
private LayoutInflater inflater;
private Context context;
@SuppressWarnings("unchecked")
public SmsListAdapter(Context ctx, int resourceId, List objects) {
super(ctx, resourceId, objects);
resource = resourceId;
inflater = LayoutInflater.from( ctx );
context=ctx;
}
@Override
public View getView (int position, View convertView, ViewGroup parent) {
//create a new view of the layout and inflate it in the row
convertView = ( RelativeLayout ) inflater.inflate( resource, null );
// Extract the object to show
Sms msg = (Sms) getItem(position);
// Take the TextView from layout and set the message
TextView lblMsg = (TextView) convertView.findViewById(R.id.lblMsg);
lblMsg.setText(msg.getBody());
//Take the ImageView from layout and set the contact image
long contactId = fetchContactId(msg.getSenderNum());
String uriContactImg = getPhotoUri(contactId).toString();
ImageView imgContactPhoto = (ImageView) convertView.findViewById(R.id.imgContactPhoto);
int imageResource = context.getResources().getIdentifier(uriContactImg, null, context.getPackageName());
Drawable image = context.getResources().getDrawable(imageResource);
imgContactPhoto.setImageDrawable(image);
return convertView;
}
}
When I attempt to activate the adapter, I get an error on the first line of getView() saying that a TextView cannot be cast to a RelativeLayout.
What I’m not clear on is why that is a TextView in the first place. My list item layout is set as a RelativeLayout and that’s what should be being inflated, unless I’m mistaken. Can anyone help me debug this?
Removing the explicit cast of
convertViewtoRelativeLayoutshould help.