Logcat error: “addView(View, LayoutParams) is not supported in AdapterView” in a ListView

泪湿孤枕 提交于 2019-11-27 07:57:44
Ander Webbs

When creating an ArrayAdapter like yours, the ArrayAdapter needs a layout resource containing just a TextView. Try changing your ArrayAdapter creation with:

setListAdapter(new ArrayAdapter<String>(this, 
      android.R.layout.simple_list_item_1, 
      this.directoryEntries));

and see if it works.

For others who have this problem and have inflated a layout in ArrayAdapter's getView, set the parent parameter to null, as in view = inflater.inflate(R.layout.mylayout, null);

Rule of thumb

You should always try to pass in a parent while inflating a View, else the framework will not be able to identify what layout params to use for that inflated view.

The correct way of handling the exception is by passing false as third parameter, this flag indicates if a view should be added directly to the passed container or not.

In the case of an adapter, the adapter itself will add the view after you returned the view from you getview method:

view = inflater.inflate(R.layout.mylayout, parent, false);

BaseAdapter sample, comes from just-for-us DevBytes:

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        View result = convertView;
        if (result == null) {
            result = mInflater.inflate(R.layout.grid_item, parent, false);
        }

        // Try to get view cache or create a new one if needed
        ViewCache viewCache = (ViewCache) result.getTag();
        if (viewCache == null) {
            viewCache = new ViewCache(result);
            result.setTag(viewCache);
        }

        // Fetch item
        Coupon coupon = getItem(position);

        // Bind the data
        viewCache.mTitleView.setText(coupon.mTitle);
        viewCache.mSubtitleView.setText(coupon.mSubtitle);
        viewCache.mImageView.setImageURI(coupon.mImageUri);

        return result;
    }

CursorAdapter sample:

    @Override
    public View newView(final Context context, final Cursor cursor, final ViewGroup root)          {
        return mInflater.inflate(R.layout.list_item_ticket, root, false);
    }

More information about view inflation can be found in this article.

Delete TextView From ListView in your XML file

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!