【问题标题】:addView() is not supported in AdapterView with nested fragments带有嵌套片段的 AdapterView 不支持 addView()
【发布时间】:2014-10-15 18:41:09
【问题描述】:

在尝试了标题已经存在的答案中提到的解决方案后,同样的错误似乎仍然存在。我正在尝试从 NavigationBar 中使用的自定义 ArrayAdapter 中为 Fragment 充气。我试图膨胀的片段本身有 2 个嵌套片段。我的预感是它与试图在 LinearLayout 中膨胀有关,但我似乎无法让这些 Fragment 膨胀。非常感谢您的帮助。

这是错误日志

10-14 21:22:57.209: E/AndroidRuntime(30555): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.inviscidlabs.schooled/com.inviscidlabs.schooled.ActivityClassEdit}: java.lang.UnsupportedOperationException: addView(View, LayoutParams) is not supported in AdapterView
10-14 21:22:57.209: E/AndroidRuntime(30555):    at android.app.ActivityThread.performLaunchActivity(ActivityThread.java)
10-14 21:22:57.209: E/AndroidRuntime(30555):    at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java)
10-14 21:22:57.209: E/AndroidRuntime(30555):    at android.app.ActivityThread.access$800(ActivityThread.java)
10-14 21:22:57.209: E/AndroidRuntime(30555):    at android.app.ActivityThread$H.handleMessage(ActivityThread.java)
10-14 21:22:57.209: E/AndroidRuntime(30555):    at android.os.Handler.dispatchMessage(Handler.java)
10-14 21:22:57.209: E/AndroidRuntime(30555):    at android.os.Looper.loop(Looper.java)
10-14 21:22:57.209: E/AndroidRuntime(30555):    at android.app.ActivityThread.main(ActivityThread.java)
10-14 21:22:57.209: E/AndroidRuntime(30555):    at java.lang.reflect.Method.invokeNative(Native Method)
10-14 21:22:57.209: E/AndroidRuntime(30555):    at java.lang.reflect.Method.invoke(Method.java:515)
10-14 21:22:57.209: E/AndroidRuntime(30555):    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java)
10-14 21:22:57.209: E/AndroidRuntime(30555):    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java)
10-14 21:22:57.209: E/AndroidRuntime(30555):    at dalvik.system.NativeStart.main(Native Method)
10-14 21:22:57.209: E/AndroidRuntime(30555): Caused by: java.lang.UnsupportedOperationException: addView(View, LayoutParams) is not supported in AdapterView
10-14 21:22:57.209: E/AndroidRuntime(30555):    at android.widget.AdapterView.addView(AdapterView.java)
10-14 21:22:57.209: E/AndroidRuntime(30555):    at android.view.LayoutInflater.inflate(LayoutInflater.java)
10-14 21:22:57.209: E/AndroidRuntime(30555):    at android.view.LayoutInflater.inflate(LayoutInflater.java)
10-14 21:22:57.209: E/AndroidRuntime(30555):    at android.view.LayoutInflater.inflate(LayoutInflater.java)
10-14 21:22:57.209: E/AndroidRuntime(30555):    at com.inviscidlabs.schooled.ContainerFragmentCriteria.onCreateView(ContainerFragmentCriteria.java:28)
10-14 21:22:57.209: E/AndroidRuntime(30555):    at android.support.v4.app.Fragment.performCreateView(Fragment.java:1504)
10-14 21:22:57.209: E/AndroidRuntime(30555):    at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:942)
10-14 21:22:57.209: E/AndroidRuntime(30555):    at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:1121)
10-14 21:22:57.209: E/AndroidRuntime(30555):    at android.support.v4.app.BackStackRecord.run(BackStackRecord.java:682)
10-14 21:22:57.209: E/AndroidRuntime(30555):    at android.support.v4.app.FragmentManagerImpl.execPendingActions(FragmentManager.java:1484)
10-14 21:22:57.209: E/AndroidRuntime(30555):    at android.support.v4.app.FragmentActivity.onStart(FragmentActivity.java:571)
10-14 21:22:57.209: E/AndroidRuntime(30555):    at android.app.Instrumentation.callActivityOnStart(Instrumentation.java)

这是代码,从违规实体开始:

public class ContainerFragmentCriteria extends Fragment{



    private FragmentManager fm;

    private boolean insertMode;

    //=====================ACTIVITY LIFECYCLE==============================
            @Override
            public View onCreateView(LayoutInflater inflater, ViewGroup container,
                Bundle savedInstanceState) {
                View v = inflater.inflate(R.layout.frag_container_criteria, container);
                return v;   
            }


        @Override
        public void onCreate(Bundle savedInstanceState){
            super.onCreate(savedInstanceState);

            //Instantiate Fragments, set Arguments
            FragmentCriteriaEdit fCrE= new FragmentCriteriaEdit();
            FragmentCriteriaList fCrL = new FragmentCriteriaList();

            Bundle fCritListArguments = new Bundle();
            fCritListArguments.putBoolean(CM.BKEY_INSERTMODE, insertMode);
            //Begin the Transaction
            fm=getChildFragmentManager();
            FragmentTransaction ft = fm.beginTransaction();
            ft.add(R.id.fccr_rootLayout, fCrE, FragmentCriteriaEdit.sTag);
            ft.add(R.id.fccr_rootLayout, fCrL, FragmentCriteriaList.sTag);
            ft.commit();

        }

        @Override
        public void onStart() {
            super.onStart();
        //Get our arguments
            Bundle args = getArguments();
            if(args!=null){
                insertMode=args.getBoolean(CM.BKEY_INSERTMODE);
            }
        }

        @Override 
        public void onDetach() { 
            super.onDetach(); 

            try { 
                Field childFragmentManager = Fragment.class.getDeclaredField("mChildFragmentManager");
                childFragmentManager.setAccessible(true);
                childFragmentManager.set(this, null);

            } catch (NoSuchFieldException e) {
                throw new RuntimeException(e);
            } catch (IllegalAccessException e) {
                throw new RuntimeException(e);
            } 
        } 



}

适配器视图。请注意,我在扩展布局时将父视图参数设置为 null:

public class ClassEditDrawerAdapter extends ArrayAdapter<ClassEditDrawerItem>{

    Context ctx;
    List<ClassEditDrawerItem> itemList;
    int layoutResID;

    public ClassEditDrawerAdapter(Context context, int layoutResourceID, List<ClassEditDrawerItem> items){
        super(context, layoutResourceID, items);
        ctx=context;
        layoutResID=layoutResourceID;
        itemList=items;
    }

    //An Effective ViewHolder, but for this Array!
    private class DrawerItemHolderThing{
        TextView itemName;
    }


     @Override
     public View getView(int position, View convertView, ViewGroup parent) {
         DrawerItemHolderThing bobSagget;
         View v = convertView;

         if(v==null){
             Log.d("adapter", "v was null");
             LayoutInflater inflater = ((Activity) ctx).getLayoutInflater();
             bobSagget= new DrawerItemHolderThing();

             v=inflater.inflate(layoutResID, null, false);

             bobSagget.itemName=((TextView) v.findViewById(R.id.item_basicItem));
             v.setTag(bobSagget);
         } else {
             bobSagget = (DrawerItemHolderThing) v.getTag();
         }


         ClassEditDrawerItem drawerItem = (ClassEditDrawerItem) this.itemList.get(position);
         if(bobSagget.itemName==null){Log.e("Adapter", "no TextView");}
         bobSagget.itemName.setText(drawerItem.getItemName());

         return v;

     }

}

活动:

public class ActivityClassEdit extends FragmentActivity{

//Variables
    //Fragments
    private ContainerFragmentCriteria frag_Criteria;


    private DrawerLayout mDrawerLayout;
    private ListView mDrawerList;
    private ActionBarDrawerToggle mDrawerToggle;


    //used as the effective ArrayAdapter for the NavigationDrawer
    private ClassEditDrawerAdapter mNavAdapter;
    private CharSequence sDrawerTitle;
    private CharSequence sTitle;

    //Serves as List of Strings to populate Nav Drawer's ListView of options
    List<ClassEditDrawerItem> navOptions;

     @Override
     protected void onCreate(Bundle savedInstanceState) {
           super.onCreate(savedInstanceState);

           setContentView(R.layout.activity_classedit);

           //Initialize List
           navOptions= new ArrayList<ClassEditDrawerItem>();
           sTitle=sDrawerTitle=getTitle();

           mDrawerLayout = (DrawerLayout) findViewById(R.id.ace_drawer);
           mDrawerList=(ListView) findViewById(R.id.ace_drawer_list);

           navOptions.add(new ClassEditDrawerItem("Criteria", R.drawable.ic_launcher));

           mNavAdapter = new ClassEditDrawerAdapter(this, R.layout.item_basic, navOptions);
           mDrawerList.setAdapter(mNavAdapter);
           //Set ListView onClickListener
           mDrawerList.setOnItemClickListener(new DrawerItemClickListener());

           //Set up the home button to open the nav drawer
           getActionBar().setDisplayHomeAsUpEnabled(true);
           getActionBar().setHomeButtonEnabled(true);

           mDrawerToggle = new ActionBarDrawerToggle(this, mDrawerLayout,
                   R.drawable.ic_launcher, R.string.hello_world,
                   R.string.name);

           mDrawerLayout.setDrawerListener(mDrawerToggle);

           //Select first item by default
           if(savedInstanceState==null){
               SelectItem(0);
           }




     }

     @Override
     public void setTitle(CharSequence title) {
           sTitle = title;
           getActionBar().setTitle(sTitle);
     }

     @Override
     protected void onPostCreate(Bundle savedInstanceState) {
           super.onPostCreate(savedInstanceState);
           // Sync the toggle state after onRestoreInstanceState has occurred.
           mDrawerToggle.syncState();
     }

     @Override
     public boolean onOptionsItemSelected(MenuItem item) {
           // The action bar home/up action should open or close the drawer.
           // ActionBarDrawerToggle will take care of this.
           if (mDrawerToggle.onOptionsItemSelected(item)) {
                 return true;
           }

           return false;
     }

     @Override
     public void onConfigurationChanged(Configuration newConfig) {
           super.onConfigurationChanged(newConfig);
           // Pass any configuration change to the drawer toggles
           mDrawerToggle.onConfigurationChanged(newConfig);
     }

     //What to do when Item is Selected
     public void SelectItem(int position){
         FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();

         switch(position){
         //Class Edit
         case 0: 
             if(frag_Criteria==null){
                 frag_Criteria = new ContainerFragmentCriteria();
             }
             transaction.replace(R.id.ace_drawer_list, frag_Criteria);
             transaction.commit();
             break;


         }

      Toast.makeText(this, String.valueOf(position), Toast.LENGTH_LONG).show();
     }


     private class DrawerItemClickListener implements ListView.OnItemClickListener {
        @Override
        public void onItemClick(AdapterView<?> parent, View view, int position,
                   long id) {
                SelectItem(position);
        }
     }

}

最后是 XML:

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


</LinearLayout>
</RelativeLayout>

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

    <LinearLayout android:id="@+id/item_ace_itemlayout"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_alignParentLeft="true"
        android:orientation="vertical"
        android:background="?android:attr/activatedBackgroundIndicator"
        >
        <LinearLayout

                  android:layout_width="fill_parent"
                  android:layout_height="wrap_content"
                  android:minHeight="55dp"
                 >

                  <ImageView
                      android:id="@+id/drawer_icon"
                      android:layout_width="wrap_content"
                      android:layout_height="wrap_content"
                      />

                  <TextView
                      android:id="@+id/drawer_itemName"
                      android:layout_width="wrap_content"
                      android:layout_height="wrap_content"
                      android:textAppearance="?android:attr/textAppearanceLarge"

                       />
              </LinearLayout>

        <View
      android:layout_width="match_parent"
      android:layout_height="1dp"
      android:layout_marginBottom="1dp"
      android:layout_marginTop="1dp"
      android:layout_marginLeft="10dp"
      android:layout_marginRight="10dp"
      android:background="#DADADC"

       ></View>

    </LinearLayout>


</RelativeLayout>

还有 Activity 的 XML:

<?xml version="1.0" encoding="utf-8"?>
<android.support.v4.widget.DrawerLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:id="@+id/ace_drawer" >

    <FrameLayout android:id="@+id/ace_frame"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        />

    <ListView 
        android:id="@+id/ace_drawer_list"
        android:layout_width="240dp"
        android:layout_height="match_parent"
        android:layout_gravity="start"
        android:choiceMode="singleChoice"
        />


</android.support.v4.widget.DrawerLayout>

【问题讨论】:

  • 如果你打算使用 null 作为根视图,不要使用第三个参数。这无关紧要。 inflater.inflate(layoutResID, null);

标签: android android-fragments navigation-drawer android-nested-fragment


【解决方案1】:

我的预感是它与试图在一个 LinearLayout,但我似乎无法让这些片段膨胀。

这不是正在发生的事情,您得到异常是因为您(主要)做错了两件事。首先,在您添加 ContainerFragmentCriteria 片段(通过 selectItem())的活动中,您使用了一个事务,该事务将片段放置在具有R.id.ace_drawer_list 的容器中。该 ID 对应于您的导航 ListView。这将失败,因为您不能只将片段添加到 ListView,您需要一个容纳容器(例如 ace_frame FrameLayout(您可能想在其中添加片段而不是列表?!))。

其次,当您在片段事务中使用 ListView 的 id 时,框架将(稍后)将带有 addView() 的片段视图添加到该容器。 ListView(以及 AdapterView 的任何子类)不支持通过 addView() 直接添加子项。在片段的 onCreateView() 中,您膨胀片段布局并将其添加到容器参数(即 ListView)中,您不应该这样做,而是:

View v = inflater.inflate(R.layout.frag_container_criteria, container, false);// false to not add the inflated layout to container

【讨论】:

  • 将此标记为答案。旧的错误得到缓解。但是,我现在得到一个“指定的孩子已经有一个父错误”。感谢您对扩大视图的见解
  • @JoshRibeiro 发布一个新问题。如果不查看您如何修改代码以及您实际在哪一行得到新异常,就很难判断出了什么问题。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多