Android ExpandableListView -UnsupportedOperationException: AdapterView 不支持 addView(View, LayoutParams)

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/10253506/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-20 03:02:00  来源:igfitidea点击:

ExpandableListView -UnsupportedOperationException: addView(View, LayoutParams) is not supported in AdapterView

androidexpandablelistviewandroid-adapterview

提问by Gaurav Arora

I am implementing Expandable List view in android and i am getting the above titled error. Please help me.

我正在 android 中实现可扩展列表视图,但出现上述错误。请帮我。

Main activity is -

主要活动是——

package com.expand;

import android.app.Activity;
import android.os.Bundle;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.View;
import android.widget.ExpandableListView;
import android.widget.Toast;


public class MyExpandableListViewActivity extends Activity {
    /** Called when the activity is first created. */



    static final String groupElements[]= {
           "India",
           "Australia",
           "England",
           "South Africa"
         };

    static final String[][] childElements=
    {
           {
          "Sachin Tendulkar",
          "Raina",
          "Dhoni",
          "Yuvi"
           },
           {
          "Ponting",
          "Adam Gilchrist",
          "Michael Clarke"
           },
           {
          "Andrew Strauss",
          "kevin Peterson",
          "Nasser Hussain"
           },
           {
          "Graeme Smith",
          "AB de villiers",
          "Jacques Kallis"
           }
            };



    DisplayMetrics metrics;
    int width;
    ExpandableListView expandList;
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);

        expandList = (ExpandableListView)findViewById(R.id.expandList1);
        metrics = new DisplayMetrics();

        getWindowManager().getDefaultDisplay().getMetrics(metrics);
        width = metrics.widthPixels;

        //ExpAdapter adapter = new ExpAdapter(MyExpandableListViewActivity.this, groupElements, childElements);

        expandList.setAdapter(new ExpAdapter(MyExpandableListViewActivity.this, groupElements, childElements));
        expandList.setIndicatorBounds(width - GetDipsFromPixel(50), width - GetDipsFromPixel(10));


        expandList.setOnGroupExpandListener(new ExpandableListView.OnGroupExpandListener() {

            @Override
            public void onGroupExpand(int groupPosition) {
                // TODO Auto-generated method stub

                 Log.e("onGroupExpand", "OK");
            }
        });

        expandList.setOnGroupCollapseListener(new ExpandableListView.OnGroupCollapseListener() {

            @Override
            public void onGroupCollapse(int groupPosition) {
                // TODO Auto-generated method stub

                Log.e("onGroupCollapse", "OK");

            }
        });

        expandList.setOnChildClickListener(new ExpandableListView.OnChildClickListener() {



            @Override
            public boolean onChildClick(ExpandableListView parent, View v,
                    int groupPosition, int childPosition, long id) {

                //getting the item that is selected
                //String s = (String) expandList.getItemAtPosition((int) id);

                Toast.makeText(MyExpandableListViewActivity.this, "You have selected :"  , Toast.LENGTH_SHORT).show();

                return false;
            }
        });

    }



    public int GetDipsFromPixel(float pixels)
    {
        // Get the screen's density scale
        final float scale = getResources().getDisplayMetrics().density;
        // Convert the dps to pixels, based on density scale
        return (int) (pixels * scale + 0.5f);
    }


}

ExpAdapter class is - I have implemented the adapter in other class and have called it in mt main activity

ExpAdapter 类是 - 我已经在其他类中实现了适配器,并在 mt main 活动中调用了它

package com.expand;

import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseExpandableListAdapter;
import android.widget.TextView;



    public class ExpAdapter extends BaseExpandableListAdapter {

        public Context myContext;
        public String[][] childElements;
        TextView childValues;
        public String[] groupElements;


        public ExpAdapter(Context context, String[] group, String[][] childs)
        {

            this.myContext=context;
            this.groupElements = group;
            this.childElements = childs;

        }



        @Override
        public Object getChild(int groupPosition, int childPosition) {
            // TODO Auto-generated method stub
            return childElements[groupPosition][childPosition];
        }

        @Override
        public long getChildId(int groupPosition, int childPosition) {
            // TODO Auto-generated method stub

            return 0;
        }

        @Override
        public View getChildView(int groupPosition, int childPosition,
                boolean isLastChild, View convertView, ViewGroup parent) {
            // TODO Auto-generated method stub

            if(convertView==null){

                LayoutInflater inflator = (LayoutInflater)myContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
                convertView  = inflator.inflate(R.layout.child_rows, parent);

            }
            childValues = (TextView)convertView.findViewById(R.id.rowValues);
            childValues.setText(childElements[groupPosition][childPosition]);

            return convertView;
        }

        @Override
        public int getChildrenCount(int groupPosition) {
            // TODO Auto-generated method stub
            return groupElements[groupPosition].length();
        }

        @Override
        public Object getGroup(int groupPosition) {
            // TODO Auto-generated method stub
            return groupElements[groupPosition];
        }

        @Override
        public int getGroupCount() {
            // TODO Auto-generated method stub
            return groupElements.length;
        }

        @Override
        public long getGroupId(int groupPosition) {
            // TODO Auto-generated method stub
            return 0;
        }

        @Override
        public View getGroupView(int groupPosition, boolean isExpanded,
                View convertView, ViewGroup parent) {
            // TODO Auto-generated method stub

            if(convertView==null){
                LayoutInflater inflator = (LayoutInflater)myContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
                convertView = inflator.inflate(R.layout.group_rows, null);
            }
            TextView group = (TextView)convertView.findViewById(R.id.groupId);
            group.setText(groupElements[groupPosition]);

            return convertView;
        }

        @Override
        public boolean hasStableIds() {
            // TODO Auto-generated method stub
            return false;
        }

        @Override
        public boolean isChildSelectable(int groupPosition, int childPosition) {
            // TODO Auto-generated method stub
            return true;
        }




    }

main.xml-

main.xml-

this is the xnl that is displayed at the first by the main activity

这是主要活动首先显示的xnl

  <?xml version="1.0" encoding="utf-8"?>
    <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"
        android:orientation="vertical" >



        <ExpandableListView 
            android:id="@+id/expandList1"
            android:layout_width="fill_parent"
            android:layout_height="fill_parent"
            >


                 <TextView 
                android:id="@+id/android:empty"
                android:layout_width="fill_parent"
                android:layout_height="fill_parent"
                >
            </TextView>


        </ExpandableListView>


    </LinearLayout>

group_row.xml

group_row.xml

this is the xml for the group elements

这是组元素的 xml

 <?xml version="1.0" encoding="utf-8"?>
    <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
        android:id="@+id/gropu_name"
        android:layout_width="fill_parent"
        android:layout_height="40dp"
        android:orientation="vertical" >


        <TextView 
            android:id="@+id/groupId"
            android:layout_height="40dp"
            android:layout_width="wrap_content"
            android:paddingLeft="30dp"
            android:gravity="center_vertical"
            android:textSize="16dp"
            android:textStyle="bold"
            />

    </LinearLayout>

child_row.xml this is the xml for the child elements

child_row.xml 这是子元素的 xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="40dp"
    android:orientation="horizontal" >

    <TextView
        android:id="@+id/rowValues"
        android:layout_width="wrap_content"
        android:layout_height="30dp"
        android:gravity="center_vertical"
        android:paddingLeft="50dp"
        android:textSize="12dp" />


</LinearLayout>

回答by Prashant Gami

Seems like Adapterview does not allow adding new view, I encountered same problem

好像 Adapterview 不允许添加新视图,我遇到了同样的问题

Solve it by replacing following line

通过替换以下行来解决它

convertView  = inflator.inflate(R.layout.child_rows, parent);

to

convertView  = inflator.inflate(R.layout.child_rows, null);

UPDATE

更新

Instead of not using a parent at all, you should simply tell the Inflater not to attach the inflated view to the parent with

而不是根本不使用父级,您应该简单地告诉 Inflater 不要将膨胀的视图附加到父级

convertView = inflator.inflate(R.layout.child_rows, parent, false); 

See also this answer.

另请参阅此答案

The reason is that adapter takes care of attaching views to parent itself.

原因是适配器负责将视图附加到父级本身。

回答by Justin

Note that you can also get this error when your layout xml is invalid.

请注意,当您的布局 xml 无效时,您也会收到此错误。

回答by B-GangsteR

As were noted above,

如上所述,

Instead of not using a parent at all, you should simply tell the Inflater not to attach the inflated view to the parent with

而不是根本不使用父级,您应该简单地告诉 Inflater 不要将膨胀的视图附加到父级

 convertView = inflator.inflate(R.layout.child_rows, parent, false);     

See also this answer.

另请参阅此答案

The reason is that adapter takes care of attaching views to parent itself.

原因是适配器负责将视图附加到父级本身。

回答by sirFunkenstine

According to Android Lint your child view should always provide a reference to its parent view when inflated. I had the exact same error in my code. Is was occurring because the TextView was placed inside the ExpandableListView. When I rearranged my xml layout the error stopped appearing.

根据 Android Lint,您的子视图在膨胀时应始终提供对其父视图的引用。我的代码中有完全相同的错误。之所以发生是因为 TextView 被放置在 ExpandableListView 中。当我重新排列我的 xml 布局时,错误不再出现。

回答by Illegal Argument

This error can also be caused because of instant runfeature. I was working on listview and because of this error app kept crashing. Uninstalling the app and running again resolved the error.

由于即时运行功能,也可能导致此错误。我正在处理 listview 并且因为这个错误应用程序一直崩溃。卸载应用程序并再次运行解决了错误。