android - MergeAdapter 与 OnClickItemListener

标签 android listview commonsware-cwac

我正在使用MergeAdapter通过 CommonsWare 合并两个 ListView。

请注意,两个 ListView 都有自己的模型。

一切都很顺利,除了当我想从合并的 ListView 中单击一个项目时,我似乎无法获得代表其相应模型的正确数据。我见过这个answer ,尽管它没有任何完整的解决方案来满足我正在寻找的问题。

这就是我实现 MergeAdapter 的方式:

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

        // merge adapter
        mAdapter  = new MergeAdapter();

        // user list
        arrUserVanities = new ArrayList<UserVanitiesModel>();
        uva = new UserVanitiesAdapter(arrUserVanities, getActivity());
        mAdapter.addAdapter(uva);

        // user category
        arrUserCategory = new ArrayList<UserCategoriesModel>();
        uca = new UserCategoryAdapter(arrUserCategory, getActivity());
        mAdapter.addAdapter(uca);


        setListAdapter(mAdapter);
   }

onItemClickListener中:

    @Override
    public void onListItemClick(ListView l, View v, int position, long id) {
        super.onListItemClick(l, v, position, id);


        UserVanitiesModel vanityModel = (UserVanitiesModel) l.getAdapter().getItem(position);
        String vanity_id = vanityModel.getVanity_id();
        String vanity_name = vanityModel.getVanity_name();


        UserCategoriesModel categoryModel = (UserCategoriesModel) l.getAdapter().getItem(position);
        String category_id = categoryModel.getCategory_id();
        String category_name = categoryModel.getCategory_name();

        Log.d(TAG, "Item clicked: "+category_name);
        Log.d(TAG, "Item clicked: "+vanity_name);

        //  mListener.onUserCategoriesSelected(category_id, category_name);
    }

我被困在这个问题上。如何在合并的 ListView 中获取相应的对象并从中获取任何数据?我将这些数据传递给接口(interface)监听器。


更新

我有两个要合并的 ListView ,即用户列表(由UserVanitiesAdapter支持)和用户类别(由支持) UserCategoriesAdapter)

这是我单击某个项目时遇到的错误:

java.lang.ClassCastException: com.example.model.usershop.UserCategoriesModel cannot be cast to com.example.model.usershop.UserVanitiesModel

如果单击第二个 ListView ,则反之亦然。

java.lang.ClassCastException: com.example.model.usershop.UserVanitiesModel cannot be cast to com.example.model.usershop.UserCategoriesModel

最佳答案

您正在调用 l.getAdapter().getItem(position) 两次并将其转换为两个不同的类。除非这些类通过继承相关,根据定义,否则将会因 ClassCastException 崩溃。

仅调用l.getAdapter().getItem(position)一次。您需要根据位置或使用instanceof运算符来确定要转换为哪个类。

关于android - MergeAdapter 与 OnClickItemListener,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22034219/

相关文章:

Android notifyDataSetChanged 不工作

android - 借助 MergeAdapter、StickyListHeaders 和 ListViewAnimations 的强大功能,我是 Android 的队长

android - 启动服务后立即调用 finish() 的正确方法

android - SwipeListView 前端点击bug 2.3 android

android - 如何在不关闭的情况下在android中的recyclerview上滑动

android - 找不到gradle android commonsware maven

java - ClassNotFoundException 公共(public)软件 CameraFragment

android - 使用联系人选择器时从具有多个号码的用户中选择一个号码

java - 如何允许在单个 Activity 上滚动多个 ListView?

android - 仅在 android 中设置顶部边距?