我正在尝试编写一个自定义适配器来将一个简单的类适应到 ListView 中。该类用于 SMS 消息,它包含简单的字段,如正文、发件人地址等。下面,请参阅我的适配器布局:
<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>
还有我的自定义适配器类:
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;
}
}
当我尝试激活适配器时,我在 getView() 的第一行收到错误消息,指出无法将 TextView 强制转换为 RelativeLayout。
我不清楚的是为什么这首先是一个 TextView 。我的列表项布局设置为RelativeLayout,这就是应该被夸大的,除非我弄错了。谁能帮我调试一下?