代码之家  ›  专栏  ›  技术社区  ›  Melody Horn

为什么ADT调用文档指定的代码会引发UnsupportedOperationException?

  •  0
  • Melody Horn  · 技术社区  · 16 年前

    res/layout/edit.xml中的我的XML布局:

    <?xml version="1.0" encoding="utf-8"?>
    <GridView 
      android:id="@+id/GridView01"
      android:layout_width="fill_parent"
      android:layout_height="fill_parent"
      xmlns:android="http://schemas.android.com/apk/res/android"
      android:numColumns="2">
    <TextView
      android:text="Person's Name"
      android:id="@+id/PersonName"
      android:layout_width="wrap_content"
      android:layout_height="wrap_content"></TextView>
    <TextView
      android:text="Person's Points"
      android:id="@+id/PersonPoints"
      android:layout_width="wrap_content"
      android:layout_height="wrap_content"></TextView>
    </GridView>
    

    当我尝试从“edit.xml”切换到“layout”时,我看到以下错误:

    java.lang.UnsupportedOperationException: addView(View, LayoutParams) is not
    supported in AdapterView
    

    我检查了adapterview的文档,这是预期的行为。那么,为什么不期望它能工作呢?

    1 回复  |  直到 16 年前
        1
  •  1
  •   Rich Schuler    16 年前

    因为你想加两个 TextView 在XML中是。不要那样做。任何视图 AdapterView 必须来自适配器。

    你得把你的 文本框 在另一个布局中包含 GridView 也。可以使用的布局有:框架布局、线性布局、相对布局、表格布局或实现自己的布局。我想你要做的是在 GRIDVIEW 您将提供一个适配器来填充它。

    <LinearLayout
        android:orientation="vertical"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"
    >
        <LinearLayout
            android:orientation="horizontal"
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
        >
            <TextView
                android:layout_width="fill_parent"
                android:layout_height="wrap_content"
                android:layout_weight="1"
            />
            <TextView
                android:layout_width="fill_parent"
                android:layout_height="wrap_content"
                android:layout_weight="1" 
            />
        </LinearLayout>
        <GridView
            android:layout_width="fill_parent"
            android:layout_height="fill_parent"
        />
    </LinearLayout>
    

    两个 文本框 因为 layout_weight 属性。以下 GRIDVIEW 将占据其余空间。

    如果你想要达到的只是拥有两个 文本框 是相邻的,但大小相同,然后使用第二个 LinearLayout 水平方向。