Android:创建3个或更多标签时的ID冲突

时间:2014-08-16 06:33:27

标签: android xml listview tabs

我在Android中有一个标签视图,标签共享相同的xml布局,它们是基于JSON动态生成的。例如,如果我有一个菜单,它将创建一个选项卡。两个菜单,两个标签。等等。 由于所有选项卡都基于相同的“菜单”对象,因此它们共享相同的xml被充气。

标签的构造没有问题。当有一个或两个标签时,更改状态和刷卡完美无瑕。当有三个或更多选项卡时,向右滑动即可,但每当我向左滑动时,我都会收到此错误:

java.lang.IllegalArgumentException: Wrong state class, expecting View State but received class android.widget.AbsListView$SavedState instead. This usually happens when two views of different type have the same id in the same hierarchy. This view's id is id/header_list_view. Make sure other views do not use the same id.

这是我的onCreateView代码:

public class MenuToListFragment extends Fragment {

HeaderListView headerListView;

// (most of the logic removed)

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {

    View rootView = inflater.inflate(R.layout.fragment_menu, container, false);
    headerListView = (HeaderListView) rootView.findViewById(R.id.header_list_view);
    return rootView;
}
}

这是我的xml布局:

<LinearLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context="<removed>.DisplayMenus">


    <com.applidium.headerlistview.HeaderListView
        android:id="@+id/header_list_view"
        android:layout_height="wrap_content"
        android:layout_width="wrap_content" />

</LinearLayout>

感谢您的帮助!

2 个答案:

答案 0 :(得分:5)

好吧,发现了这个错误! 使用方法OnActivityCreated,当调用HeaderListView时,我不得不使用headerListView.setId()分配一个唯一的Id;对于此id的值,我必须使用setArguments和getArguments通过包传递选项卡的位置。我尚未探索的一种方法是使用headerListView.setId(headerListView.generateViewId())生成Id。

现在,关于“为什么”只有在有3个视图或更多视图时才会发生。这是我猜的地方,我喜欢一些反馈。当一个标签膨胀时,我发现只有邻居被保存在内存中(另一个被丢弃?)。如果左侧或右侧的两个选项卡不会生成或恢复视图,因为该组(邻居使用选项卡)始终相同。现在,如果我有3个标签并一直向右滑动,则第一个标签会进入睡眠状态。向后滑动到第二个选项卡会强制android将第一个选项卡从其睡眠状态恢复。由于睡眠标签与其他标签具有相同的ID,因此会产生冲突。瞧!

希望这有助于人们遇到同样的问题

答案 1 :(得分:4)

我改变了布局定义:

<com.applidium.headerlistview.HeaderListView
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:tag="HeaderListView" />

然后使用标记查找视图:

mHeaderListView = (HeaderListView) view.findViewWithTag("HeaderListView"); 

它似乎有效,不再是java.lang.IllegalArgumentException