其他分享
首页 > 其他分享> > ArrayAdapter requires the resource ID to be a TextView

ArrayAdapter requires the resource ID to be a TextView

作者:互联网

错误代码:

ListItem2Adapter adapter = new ListItem2Adapter(ListItem2Activity.this,R.layout.list_item_pic,data);

ListItem2Adapter.java :

public class ListItem2Adapter extends ArrayAdapter<ListItemPic> {
    private int resourceId;

    public ListItem2Adapter(Context context, int resourceId, List<ListItemPic> data){
        super(context,resourceId,data);
        this.resourceId = resourceId;
    }

    @NonNull
    @Override
    public View getView(int position, @Nullable View convertView, @NonNull ViewGroup parent) {
        ListItemPic item = getItem(position);
        View view = LayoutInflater.from(getContext()).inflate(resourceId,parent,false);
        ImageView ivItem = view.findViewById(R.id.iv_list_item_left_icon);
        TextView tvItem = view.findViewById(R.id.tv_list_item_pic_text);

        ivItem.setImageResource(item.getImageId());
        tvItem.setText(item.getText());
        return view;
    }
}

R.layout.list_item_pic:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent" android:layout_margin="10dp">

    <ImageView
        android:id="@+id/iv_list_item_left_icon"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"/>
    <TextView
        android:id="@+id/tv_list_item_pic_text"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginLeft="10dp"
        android:layout_gravity="center_vertical"
        />
</LinearLayout>

错误原因:ArrayAdapter的第二个参数,该资源必须是个TextView
解决方案:把上面的xml中的根节点换成TextView

标签:resource,ArrayAdapter,resourceId,list,item,ListItem2Adapter,requires,TextView,vi
来源: https://www.cnblogs.com/zhenhunfan2/p/13983687.html