notifyDataSetChanged 更新ListView失败

2023-11-27

I have a DialogFragment which has a list view with CheckedTextView and a checkbox at the top to Check and uncheck all the items in the list view. I am trying to set the State of the CheckedTextView to Checked/Unchecked depending on the state of the CheckAll Check box. But i am not able to update the view accordingly using notifyDataSetChanged. enter image description here

类别DialogFragment.java

public class CategoriesDialogFragment extends SherlockDialogFragment {
    CheckBox checkAll;
    ListView categoriesListView;
    CategoriesListAdapter adapter;
    static Category category;

    String[] categories = new String[] { "Hill Station", "Beach", "Historic",
            "Wild Life", "Waterfall", "River", "Archeology", "Hill Station",
            "Beach", "Historic", "Wild Life", "Waterfall", "River",
            "Archeology" };
    Boolean[] categories_state = new Boolean[] { true, false, true, true, true,
            true, false, true, false, true, true, true, true, false };

    public static CategoriesDialogFragment newInstance() {
        CategoriesDialogFragment frag = new CategoriesDialogFragment();
        Bundle args = new Bundle();
        frag.setArguments(args);
        return frag;
    }

    @Override
    public Dialog onCreateDialog(Bundle savedInstanceState) {
        final Dialog dialog = new Dialog(MainActivity.context);
        dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);

        dialog.setContentView(R.layout.dialog_categories);

        categoriesListView = (ListView) dialog
                .findViewById(R.id.listViewDialog);

        List<Category> theCategories = new ArrayList<Category>();
        for (int i = 0; i < categories.length; i++) {
            Boolean flag;
            Category pl = new Category(categories[i], categories_state[i]);
            theCategories.add(pl);
        }

        // categoriesListView.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE);
        adapter = new CategoriesListAdapter(MainActivity.context,
                R.layout.dialog_list_item_category, theCategories);

        categoriesListView.setAdapter(adapter);

        // List View Item Click Listener
        categoriesListView
                .setOnItemClickListener(new AdapterView.OnItemClickListener() {

                    @Override
                    public void onItemClick(AdapterView<?> parent, View view,
                            int position, long id) {
                        // TODO Auto-generated method stub
                        CategoriesListAdapter adapter = (CategoriesListAdapter) parent
                                .getAdapter();
                        Category c = (Category) adapter.getItem(position);
                        c.setChecked(!c.getChecked());
                        adapter.notifyDataSetChanged();
                    }

                });


        // CheckAll CheckBox
        checkAll = (CheckBox) dialog.findViewById(R.id.checkBoxAll);
        checkAll.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {

            @Override
            public void onCheckedChanged(CompoundButton buttonView,
                    boolean isChecked) {

                Toast.makeText(MainActivity.context, "Check",
                        Toast.LENGTH_SHORT).show();
                for (int i = 0; i < adapter.getCount(); i++) {
                    categoriesListView.setItemChecked(i, isChecked);
                    Log.i("Nomad", isChecked + " isChecked " + i);
                }
                adapter.notifyDataSetChanged();

                /*
                 * if (isChecked) { Log.i("Nomad", "isChecked"); for (int i = 0;
                 * i < adapter.getCount(); i++) { category = adapter.getItem(i);
                 * category.setChecked(true); Log.i("Nomad", "isChecked "+i); }
                 * adapter.notifyDataSetChanged(); } else { Log.i("Nomad",
                 * "isUnChecked"); for (int i = 0; i < adapter.getCount(); i++)
                 * { category = adapter.getItem(i); category.setChecked(false);
                 * Log.i("Nomad", "isUnChecked "+i); }
                 * adapter.notifyDataSetChanged(); }
                 */

            }
        });
        return dialog;

    }

    private static class CategoriesListAdapter extends ArrayAdapter<Category> {
        public Context mContext;

        List<Category> mCategories;

        public CategoriesListAdapter(Context context, int resource,
                List<Category> categories) {
            super(context, resource, categories);
            // TODO Auto-generated constructor stub
            this.mCategories = categories;
            this.mContext = context;

        }

        public int getCount() {
            return mCategories.size();
        }

        @Override
        public Category getItem(int position) {
            // TODO Auto-generated method stub
            return mCategories.get(position);
        }

        @Override
        public long getItemId(int position) {
            return position;
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {

            ViewHolder holder;

            if (convertView == null) {
                LayoutInflater viewInflater;
                viewInflater = LayoutInflater.from(getContext());
                convertView = viewInflater.inflate(
                        R.layout.dialog_list_item_category, null);

                holder = new ViewHolder();
                holder.categoryName = (CheckedTextView) convertView
                        .findViewById(R.id.categories_checkbox);

                convertView.setTag(holder);

            } else {
                holder = (ViewHolder) convertView.getTag();
            }

            holder.categoryName.setText(mCategories.get(position)
                    .getCategoryName());
            holder.categoryName.setChecked(mCategories.get(position)
                    .getChecked());

            return convertView;
        }

        static class ViewHolder {
            CheckedTextView categoryName;
        }
    }
}

类别.java

public class Category {
    String categoryName = "";
    private boolean checked = false;

    public Category(String categoryName, boolean checked) {

        this.categoryName = categoryName;
        this.checked = checked;

    }

    public String getCategoryName() {
        return categoryName;
    }

    public void setCategoryName(String categoryName) {
        this.categoryName = categoryName;
    }

    public boolean getChecked() {
        return checked;
    }

    public void setChecked(boolean checked) {
        this.checked = checked;
    }

}

对话框类别.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/parentPanel"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_marginEnd="8dip"
    android:layout_marginStart="8dip"
    android:background="@color/primary_white"
    android:orientation="vertical" >

    <LinearLayout
        android:id="@+id/title_template"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginEnd="16dip"
        android:layout_marginStart="16dip"
        android:gravity="center_vertical|start"
        android:orientation="horizontal"
        android:paddingTop="5dp" >

        <TextView
            android:id="@+id/textView1"
            style="?android:attr/textAppearanceLarge"
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:paddingLeft="10dp"
            android:text="@string/dialog_category_title"
            android:textColor="@color/primary_color"
            android:textSize="22sp" />

        <TextView
            android:id="@+id/all"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="@string/dialog_category_checkbox"
            android:textColor="@color/primary_color" />

        <CheckBox
            android:id="@+id/checkBoxAll"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:paddingRight="6dp" />
    </LinearLayout>

    <View
        android:id="@+id/titleDivider"
        android:layout_width="match_parent"
        android:layout_height="2dip"
        android:background="@color/black" />

    <LinearLayout
        android:id="@+id/contentPanel"
        android:layout_width="match_parent"
        android:layout_height="0dp"
        android:layout_weight="1"
        android:minHeight="64dp"
        android:orientation="vertical" >

        <ListView
            android:id="@+id/listViewDialog"
            android:layout_width="match_parent"
            android:layout_height="wrap_content" >
        </ListView>
    </LinearLayout>

    <LinearLayout
        android:id="@+id/buttonPanel"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="vertical" >

        <Button
            android:id="@+id/button_category_ok"
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:text="@string/dialog_category_btn_ok"
            android:textSize="14sp" />
    </LinearLayout>

</LinearLayout>

dialog_list_item_category.xml

<?xml version="1.0" encoding="utf-8"?>
<CheckedTextView xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/categories_checkbox"
    android:layout_width="fill_parent"
    android:layout_height="?android:attr/listPreferredItemHeight"
    android:checkMark="?android:attr/listChoiceIndicatorMultiple"
    android:gravity="center_vertical"
    android:onClick="toggle"
    android:paddingBottom="10dp"
    android:paddingLeft="10dp"
    android:paddingRight="12dp"
    android:paddingTop="10dp"
    android:text="sss" />

我正在尝试将 CheckedTextView 的状态设置为 选中/取消选中取决于 CheckAll 复选框的状态。 但我无法使用相应地更新视图 通知数据集更改。

添加了带有问题代码的示例作为我的答案的示例。它有效并且可以在这里找到(看看它)。

另外,Android开发人员的答案是有效的,因为每次用户检查/取消选中所有项目时,您基本上都会使用具有正确状态的新项目来重置适配器。CheckBoxs。这可能会造成浪费(但如果列表相对较小,则可以接受)。另请记住,如果categoryName of the Category对话框中的类发生更改,您需要确保构造新的Categories使用正确的名称(如果您不修改类别名称那么这不是问题),当所有CheckBox被采取行动。

尝试这样的事情:

  1. 去除categoriesListView.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE);如果它在你的代码中
  2. 修改OnCheckedChangeListener用于检查所有CheckBox像这样:

            @Override
            public void onCheckedChanged(CompoundButton buttonView,
                    boolean isChecked) {
    
                Toast.makeText(getActivity(), "Check", Toast.LENGTH_SHORT)
                        .show();
    
                Log.i("Nomad", "isChecked");
                for (int i = 0; i < adapter.getCount(); i++) {
                    adapter.getItem(i).setChecked(isChecked);
                    Log.i("Nomad", "isChecked " + i);
                }
                adapter.notifyDataSetChanged();
            }
    
  3. add an OnItemClickListener给你的类别列表视图 ListView像这样:

                    @Override
                    public void onItemClick(AdapterView<?> arg0, View arg1,
                            int arg2, long arg3) {
                        CategoriesListAdapter adapter = (CategoriesListAdapter) arg0
                                .getAdapter();
                        Category c = (Category) adapter.getItem(arg2);
                        c.setChecked(!c.getCheckStatus());
                        adapter.notifyDataSetChanged();
                    }
    
  4. the setChecked(boolean) and getCheckStatus()(我看到你有一个isChecked中的方法Category您可以使用它来获取布尔状态)是您的方法Category用于设置和获取该项目的状态的类

  5. in the getView()适配器的方法,设置状态如下:

    holder.categoryName.setChecked(mCategories.get(position)
                    .getCheckStatus());
    
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

notifyDataSetChanged 更新ListView失败 的相关文章

随机推荐

  • Windows Azure 上的 32 位旧版 COM DLL

    我在我的 Web 应用程序中使用大约 15 20 个旧版 32 位 C COM DLL 其中一些 32 位 DLL 具有第 3 方依赖项 这些依赖项是 DLL 的 COM 或本机依赖项 我正在考虑迁移到 Windows Azure 据我所知
  • 使用字节的 AWS Rekognition JavaScript SDK

    The AWS Rekognition Javascript API指出对于rekognition compareFaces params 方法 将SourceImage and TargetImage可以采取Bytes or S3Obje
  • 使用 AVAssetReader 绘制波形

    我使用 assetUrl 从 iPod 库中读取歌曲 代码中名为 audioUrl 我可以用多种方式演奏它 我可以剪切它 我可以用它做一些处理 但是 我真的不明白我要用这个 CMSampleBufferRef 做什么来获取绘制波形的数据 我
  • Facebook init() 的 channelUrl 参数是否已弃用?

    我记得有一个channelUrl选项FB init 但根据这一页 此功能是否已弃用 是的 不再需要channelUrl 以下是博客文章中的引用 更改了 JavaScript SDK 的浏览器要求 为了使 JavaScript SDK 能够与
  • include "file.h" 与 有什么区别?

    我正在 Visual studio 2010 中工作 我在项目属性 gt 链接器 gt 常规 gt 其他目录中添加了一个目录 如果我使用该项目可以编译 file h 但如果我使用则不会
  • 如何使用 Java 中的 DateFormat 解析月份完整形式字符串?

    我试过这个 DateFormat fmt new SimpleDateFormat MMMM dd yyyy Date d fmt parse June 27 2007 error Exception in thread main java
  • 工具提示和弹出窗口在 Bootstrap 5 中不起作用

    我使用 Bootstrap 5 创建了一个非常小的网站 我使用 工具提示 和 弹出窗口 在页面底部创建了 2 个按钮 但它们不起作用 没有显示任何内容 这是我的网站 位于页面底部 https www mathieulebert fr 这是
  • Java:将多个数组交错成一个数组

    I found similar关于将两个数组列表交错为一个的问题 但它是在 PHP 中 我在面试中也被问到这个问题 但无法解决 回到SO看看是否已经解决 但我只能找到这个paper 那么有指向伪代码或方法定义的指针吗 Big O 限制 O
  • 为什么临时获取右值地址是非法的?

    根据 如何绕过警告 右值用作左值 Visual Studio 只会对如下代码发出警告 int bar return 3 void foo int ptr int main foo bar 在 C 中是不允许获取临时地址 或者至少是由某个对象
  • 使用 2 种可能的布局查看绑定,将绑定变量分配给 2 个生成的绑定类

    所需功能 我有一个活动 它有一个从后端收到的值 该值指示使用两种布局之一 我们称这个值为布局类型为了简单起见 在下面的示例代码中我们假设我们不关心它将如何分配 因此 我有两个布局 xml 文件 我们称它们为布局1 xml 布局2 xml 执
  • 在头文件与实现文件目标 c 中定义属性

    在基于页面的应用程序模板中 我在实现 m 文件中经常看到这种情况 interface ModelController property readonly strong nonatomic NSArray pageData end 为什么不在
  • 需要使用虚拟化和按需加载的 WPF TreeView 搜索示例

    我需要在WPF中实现搜索功能TreeView 基本上我需要记住最后的用户选择 我尝试过建议的各种方法 但没有任何效果virtualization已在我的中启用TreeView并且子节点仅在父节点展开时才加载 延迟加载 有人知道有一个示例同时
  • 将计算机加入工作组

    如何查询特定工作组中所有可访问的计算机 您可以使用活动目录 API 检查目录项类 不要忘记添加对System DirectoryServices dll 这是一个简短的例子 using DirectoryEntry workgroup ne
  • 通过管道发送多个文件

    我们正在使用express 4 现在我有这样的东西 var express require express router express Router router get local modules function req res ne
  • 谷歌地图 API,提供的 API 密钥无效

    这是我第一次在堆栈溢出上发布问题 真心希望大家能帮忙 我第一次尝试使用谷歌地图地理编码 api 但无法让它工作 我使用的网址格式是 https maps googleapis com maps api geocode json addres
  • Qt 应用程序 UI 元素在 Docker 中随机呈现为空白/黑色

    我准备了Dockerfile构建我的 Docker 镜像Qt应用程序 要运行应用程序 我使用 X 我启用对 X 服务器的访问 xhost local root 然后我使用以下命令来运行它 docker run it env DISPLAY
  • 保留的 Python 模块/包名称是什么?

    我在使用 Python 单元测试时遇到了一个奇怪的错误 我的项目中有两个文件夹 project code init py empty app py defines my App class test test py contains my
  • 快速 firestore 检查文档是否存在

    使用 swift 和 firestore 我想检查 已使用的用户名 集合以查看用户名是否已被使用 以及它是否已提醒用户它已被使用 否则如果它仍然可用 我想创建该文件 我想要做的要点概述如下 我可以毫无问题地保存数据 尽管它检查其文档是否存在
  • 如何让RACSignal变热?

    ReactiveCocoa 可以通过调用它的方法将信号转换为 热 信号 subscribeCompleted 但我认为如果您不关心结果 即没有订阅者 则此方法非常冗长 RACDisposable animationDisposable se
  • notifyDataSetChanged 更新ListView失败

    I have a DialogFragment which has a list view with CheckedTextView and a checkbox at the top to Check and uncheck all th