如何从复选框数组中保存布尔状态并在使用 SharedPreferences 加载适配器时加载其状态

2024-04-30

我有一个用于列表视图的 CustomAdapter,我需要使用 SharedPreferences 保存布尔数组中的所有复选框状态,我想将技巧的名称(字符串数组)保存为键和每个技巧的状态。

我想到的 SharedPreferences 示例:

(“技巧名称”,假/真) (“ATW - 环游世界”,假/真)

每次用户更改任何状态时,都需要在 SharedPreference 内更新以获取单击的技巧。

我尝试了以下两种方法来测试,但它不起作用,我不知道如何使其起作用。

storeArray() 和 loadArray()。

带有复选框的列表视图 https://i.stack.imgur.com/o3WGY.png

public class CustomAdapter0 extends BaseAdapter {

    public CustomAdapter0(String[] tricks, Context context) {
        this.tricks = tricks;
        this.context = context;
        isClicked = new boolean[tricks.length];
        for(int i = 0; i < isClicked.length; i++) isClicked[i] = false;

    }

    private String[] tricks;
    private Context context;
    private boolean[] isClicked;
    private LayoutInflater layoutInflater;


    @Override
    public int getCount() {
        return tricks.length;
    }

    @Override
    public Object getItem(int i) {
        return tricks[i];
    }

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

    @Override
    public View getView(final int i, View convertView, ViewGroup viewGroup) {

        View row = convertView;

        if(convertView == null){

            layoutInflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
            row = layoutInflater.inflate(R.layout.custom_listview_tricks, null);
        }

        TextView textView = row.findViewById(R.id.name_xml);
        ImageButton imageButton = row.findViewById(R.id.unmastered_xml);

        textView.setText(tricks[i]);
        if (isClicked[i]) imageButton.setBackgroundResource(R.drawable.mastered);
        else imageButton.setBackgroundResource(R.drawable.unmastered);



        **loadArray**(tricks[i], context);


        imageButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {

                ImageButton clickedView = (ImageButton) view;
                int clickedPosition = (int)clickedView.getTag();
                isClicked[clickedPosition] = !isClicked[clickedPosition];
                notifyDataSetChanged();

                **storeArray**(isClicked, tricks, context);

            }
        });

        imageButton.setTag(i);

        return row;
    }

    public boolean **storeArray**(boolean[] array, String[] arrayName, Context mContext) {

        SharedPreferences prefs = mContext.getSharedPreferences("preferencename", 0);
        SharedPreferences.Editor editor = prefs.edit();
        editor.putInt(arrayName +"_size", array.length);

        for(int i=0;i<array.length;i++)
            editor.putBoolean(arrayName + "_" + i, array[i]);

        return editor.commit();
    }


    public Boolean[] **loadArray**(String arrayName, Context mContext) {

        SharedPreferences prefs = mContext.getSharedPreferences("preferencename", 0);
        int size = prefs.getInt(arrayName + "_size", 0);
        Boolean array[] = new Boolean[size];
        for(int i=0;i<size;i++)
            array[i] = prefs.getBoolean(arrayName + "_" + i, false);

        return array;
    }

}

TricksActivity 与布尔数组

public class TricksActivity extends AppCompatActivity {

    private String[] lower = {

            "ATW - Around the World",
            "HTW - Hop the World",
            "Crossover",
            "Crossover 360",
            "Simple Crossover",
            "Reverse Crossover",
            "KATW - Knee Around the World",
            "KHTW - Knee Hop the World",
            "Toe Bounce",
            "Reverse Toe Bounce",
            "Air Jester",
            "ATL - Around the Leg",
            "Hell Juggles",
            "AATW - Abbas Around the World",
            "HATW - Half Around the World",
            "TATW - Touzani Around the World",
            "MATW - Mitchy Around the World",
            "ATATW - AlternateTouzani Around the World",
            "AMATW - Alternate Mitchy Around the World",
            "HMATW - Homie Mitchy Around the World",
            "HTATW - Homie Touzani Around the World",
            "KAATW - Knee Abbas Around the World",
            "KMATW - Knee Mitchy Around the World",
            "KTATW - Knee Touzani Around the World",
            "LEBATW - Lebioda Around the World",
            "LATW - Lemmens Around the World",
            "MAATW - Mitchy Abbas Around the World",
            "RATW - Ratinho Around the World",
            "ATL - Around the Leg",
            "360 ATW",
            "Clipper",
            "JATOW - Joshua Around the Oppositive World",
            "Sagami Aroudn the World",
            "YATW - Yosuke Around the World",
            "Timo ATW",
            "Knee Timo ATW",
            "Air Jester",
            "Eclipse",
            "Half New Shit",
            "ALATW - Alternate Lemmens Around the World",
            "BATW - Beck Around the World",
            "HJATW - Homie Jay Around the World",
            "HMAATW - Homie Mitchy Abbas Around the World",
            "HTAATW - Homie Touzani Abbas Around the World",
            "KAMATW - Knee Alternate Mitchy Around the World",
            "KATATW - Knee Alternate Touzani Around the World",
            "KMAATW - Knee Mitchy Alternate Around the World",
            "LAATW - Lemmens Abbas Around the World",
            "LMATW - Lemmens Mitchy Around the World",
            "LTATW - Lemmens Touzani Around the World",
            "Magellan",
            "New Shit",
            "Palle Trick",
            "Reverse Palle Trick",
            "Toe Stall",
            "Hell Stall",
            "Knee Stall",
            "Hell Juggles",
            "Spin Magic",
            "MichRyc Move",
            "AHMATW - Alternate Homie Mitchy Around the World",
            "AHTATW - Alternate Homie Touzani Around the World",
            "ALMATW - Alternate Lemmens Mitchy Around the World",
            "KLAATW - Knee Lemmens Abbas Around the World",
            "SATW - Skora Around the World",
            "Skora Move",
            "RSATW - Reverse Skora Around the World",
            " HTLATW - Homie Touzani Lemmens Around the World",
            "SZATW - Szymo Around The World",
            "EATW - Eldo Around the World",
            "SKATW - Skala Around the World",
            "ZATW - Zegan Around the World",
            "K3EATW - K3vin Eldo Around the World",
            "SKMATW - Skala Mitchy Around the World",
            "EMATW - Eldo Mitchy Around the World",
            "AEATW - Alternate Eldo Around the World",
            "PATW - Palle Around the World",
            "PMATW - Palle Mitchy Around the World",
            "APATW - Alternate Palle Around the World"

    };

    private String[] upper = {

            "Head Stall",
            "Top Head Stall",
            "Side Head Stall",
            "Shoulder Stall",
            "Neck Stall",
            "360",
            "Chest Stall",
            "ATM - Around The Moon",
            "Carousel",
            "Pavel Roll",
            "LIP Stall",
            "Arm Roll",
            "Nose Stall",
            "Neck Flick",
            "LATM - Luki Around the Moon",

    };
    private String[] sitDown = {

            "Shin Stall",
            "Sole Stall",
            "Abdullah",
            "Sole Juggle",
            "Shin ATW",
            "Dimetto"

    };
    private String[] combosFamosos= {

            "CNK NT Combo",
            "Skóra NT Combo",
            "Palle Combo",
            "Palle Combo 2"

    };

    private ImageView imageView;


    private int codigo;
    ListView listView;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_tricks);

        Intent intent = getIntent();
        codigo = intent.getIntExtra("codigo", 0);

        //Toast.makeText(this, ""+codigo, Toast.LENGTH_SHORT).show();

        listView = findViewById(R.id.listview_xml);


        if (codigo == 0){
            CustomAdapter0 customAdapter0 = new CustomAdapter0(lower, TricksActivity.this);
            listView.setAdapter(customAdapter0);

        }if (codigo == 1){

            CustomAdapter0 customAdapter0 = new CustomAdapter0(upper, TricksActivity.this);
            listView.setAdapter(customAdapter0);

        }if (codigo == 2){

            CustomAdapter0 customAdapter0 = new CustomAdapter0(sitDown, TricksActivity.this);
            listView.setAdapter(customAdapter0);

        }if (codigo == 3){

            CustomAdapter0 customAdapter0 = new CustomAdapter0(combosFamosos, TricksActivity.this);
            listView.setAdapter(customAdapter0);

        }if (codigo == 4){


        }

        listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {

                Intent intent = new Intent(getApplicationContext(), VideoActivity.class);

                if(codigo == 0){

                    //Toast.makeText(TricksActivity.this, ""+lower[i], Toast.LENGTH_SHORT).show();
                    intent.putExtra("trick", lower[i]);

                }
                if(codigo == 1){

                    //Toast.makeText(TricksActivity.this, ""+upper[i], Toast.LENGTH_SHORT).show();
                    intent.putExtra("trick", upper[i]);

                }
                if(codigo == 2){

                    //Toast.makeText(TricksActivity.this, ""+sitDown[i], Toast.LENGTH_SHORT).show();
                    intent.putExtra("trick", sitDown[i]);

                }
                if(codigo == 3){

                   //Toast.makeText(TricksActivity.this, ""+combosFamosos[i], Toast.LENGTH_SHORT).show();
                    intent.putExtra("trick", combosFamosos[i]);

                }
                startActivity(intent);
                }

            });

    }

}

尝试这个适配器代码:

public class CustomAdapter0 extends BaseAdapter {
public CustomAdapter0(String listname, String[] tricks, Context context) {
    this.tricks = tricks;
    this.context = context;
    isClicked = new boolean[tricks.length];
    for(int i = 0; i < isClicked.length; i++) isClicked[i] = false;
    this.listname = listname;
}

private String[] tricks;
private Context context;
private boolean[] isClicked;
private LayoutInflater layoutInflater;
private String listname;

@Override
public int getCount() {
    return tricks.length;
}

@Override
public Object getItem(int i) {
    return tricks[i];
}

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

@Override
public View getView(final int i, View convertView, ViewGroup viewGroup) {

    View row = convertView;
    if(convertView == null){
        layoutInflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        row = layoutInflater.inflate(R.layout.custom_listview_tricks, null);
    }
    TextView textView = row.findViewById(R.id.name_xml);
    ImageButton imageButton = row.findViewById(R.id.unmastered_xml);

    textView.setText(tricks[i]);
    if (isClicked[i]) imageButton.setBackgroundResource(R.drawable.mastered);
    else imageButton.setBackgroundResource(R.drawable.unmastered);

    imageButton.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            ImageButton clickedView = (ImageButton) view;
            int clickedPosition = (int)clickedView.getTag();
            isClicked[clickedPosition] = !isClicked[clickedPosition];
            notifyDataSetChanged();

            storeArray();
        }
    });
    imageButton.setTag(i);
    return row;
}

public boolean storeArray() {
    SharedPreferences prefs = context.getSharedPreferences(listname, Context.MODE_PRIVATE);
    SharedPreferences.Editor editor = prefs.edit();
    for(int i = 0; i < tricks.length; i++)
        editor.putBoolean(tricks[i], isClicked[i]);
    return editor.commit();
}

public void loadArray() {
    SharedPreferences prefs = context.getSharedPreferences(listname, Context.MODE_PRIVATE);
    for(int i = 0; i < tricks.length; i++)
        isClicked[i] = prefs.getBoolean(tricks[i], false);
}
}

在 Activity 中,更改用于初始化适配器的 if 语句,例如:

       if (codigo == 0){
        CustomAdapter0 customAdapter0 = new CustomAdapter0("lower", lower, TricksActivity.this);
        listView.setAdapter(customAdapter0);
        customAdapter0.loadArray();

    }if (codigo == 1){

        CustomAdapter0 customAdapter0 = new CustomAdapter0("upper", upper, TricksActivity.this);
        listView.setAdapter(customAdapter0);
        customAdapter0.loadArray();

    }if (codigo == 2){

        CustomAdapter0 customAdapter0 = new CustomAdapter0("sitDown", sitDown, TricksActivity.this);
        listView.setAdapter(customAdapter0);
        customAdapter0.loadArray();

    }if (codigo == 3){

        CustomAdapter0 customAdapter0 = new CustomAdapter0("combosFamosos", combosFamosos, TricksActivity.this);
        listView.setAdapter(customAdapter0);
        customAdapter0.loadArray();
    }

希望有帮助!

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

如何从复选框数组中保存布尔状态并在使用 SharedPreferences 加载适配器时加载其状态 的相关文章

随机推荐

  • 在集线器外部获取 SignalR 用户 (Hub.Context)

    有没有办法在集线器之外获取当前的 signalR 请求用户 我可以在集线器方法内部使用 Hub Context User 但是如果集线器方法调用任何其他底层 Wcf 服务调用 附加的BehaviorExtensionElement 用于添加
  • Java Web 启动和安全性

    刚刚有人向我指出 我的博客中的 Java Web Start 应用程序 例如我的按键绑定 http tips4java wordpress com 2008 10 10 key bindings 条目 由于以下安全错误而不再起作用 经过一些
  • 如何将 UTC 日期时间转换为另一个时区?

    我怎样才能转换这样的日期 2012 07 16 01 00 00 00 它在UTC 00 00时区 到UTC 04 00时区 确保正确处理夏令时 Use DateTime http php net manual en class datet
  • 检测 vb.net 中的浏览器关闭事件

    我的网页如下所示
  • 如何使用 Trie 进行拼写检查

    我有一个根据单词词典构建的特里树 我想用它来进行拼写检查 并建议字典中最接近的匹配项 也许对于给定数量的编辑x 我想我会在目标单词和字典中的单词之间使用 levenshtein 距离 但是有没有一种聪明的方法可以遍历 trie 而不需要对每
  • 找不到 R.layout.activity_main

    我试图使用一些在线教程来解决多种布局 问题是只要只有一个 XML 文件 我的程序就可以正确构建和编译 当我添加多个 XML 文件时 我收到错误消息 指出该行的 activity main 无法解析或不是字段 setContentView R
  • 无法从 GetProcessId(.. hWnd) (pInvoke) 中提取 processID

    我使用以下方法 DllImport kernel32 dll SetLastError true static extern int GetProcessId IntPtr hWnd 尝试获取正在运行的进程的 processId 我拥有的唯
  • 在应用商店上发布 PWA:google play 和 ios itunes

    有没有办法在应用商店上发布 PWA 来发布应用 谷歌播放和 iOS iTunes 不用用科尔多瓦制造一辆越野车 这会带来大量的维护问题 是的 有办法将您的 PAW 发布到 Android 应用商店 TWAs可信 Web 活动是一种使用基于自
  • MySQL - 选择字符串的前 10 个字节

    各位聪明的男士女士们 大家好 如何选择字符串的前 x 个字节 用例 我正在优化产品描述文本以上传到亚马逊 亚马逊按 utf8 中的字节 不是我之前所说的 latin1 而不是字符来测量字段长度 另一方面 MySQL 似乎是基于字符进行操作的
  • 两个 primefaces 日历组件验证

    我有一个表格JSF 2我使用双字段来指定日期范围 这样做的目的是不让用户选择第二个日期之前的第一个日期 所以我想在发送表单之前执行验证 使用p calendar成分 我所做的是将验证器绑定到第二个日历输入 以便在内部访问第一个组件并比较日期
  • 测试 powermock 模拟客户端调用的 http 服务器超时

    我需要为 connectTimeout 和 SocketTimeout 异常编写测试用例 我使用 powerMock 创建模拟对象 下面是我的代码 但是我的模拟对象出现空指针异常 任何帮助表示赞赏 package com util impo
  • 如何使用 JSON 和 Perl (HTML::Mason) 通过 AJAX 创建动态网页?

    我对处理 Javascript JSON 和 Peel 的方式感到有些困惑 而且大多数示例都是 PHP 语言 这对我没有帮助 我有一个页面 称为 main html 其中包含来自 MySQL 的数据 并且可以选择按 id 删除行 然后我让
  • 如何使用可滑动选项卡实现 PageTransformer

    在我的示例代码中 我在 MainActivity java 中有三个可滑动选项卡 即 Android IOS 和 WINDOWS 我使用滑动在选项卡之间切换 现在 我必须使用可滑动选项卡实现 PageTransformer 所以这里我需要您
  • Yii:如何用另一个模型数据填充选择输入?

    我正在玩一个小应用程序以学习使用 Yii 我创建了一个小型网络应用程序 其中包含 2 个模型 表 项目和任务 一对多关系 在模型类中正确配置 我现在尝试自定义任务 创建视图 用建议可用项目列表的选择框替换文本输入字段 我打开表单视图并尝试了
  • “分支”到底是什么意思?

    长话短说 据我所知 术语 分支 Git 术语 可能指的是相关但不同的事物 指向提交的非符号引用 指针 此类引用的名称 例如 master 存储库提交 DAG 的子图 由此类引用所指向的提交可到达的所有提交组成 然而 我发现这个术语显然指的是
  • 并发 log4j

    我有自己的日志引擎 它将日志写入带有阻塞队列的单独线程上 为了使用 标准软件 我正在考虑切换到 log4j 我不希望我的高并发软件因日志命令而变慢 这些日志命令在调用命令时将所有内容写入磁盘 log4j 可以用作垃圾箱吗 Log4j 是大多
  • python 解码部分 utf-8 字节数组

    我从不了解 UTF 8 规则的通道获取数据 因此 有时当 UTF 8 使用多个字节来编码一个字符并且我尝试将部分接收到的数据转换为文本时 我在转换过程中遇到错误 根据接口的性质 没有任何结束的流 我无法找出数据何时已满 因此我需要处理部分
  • 如何配置 apache 服务器与 HTTPS 后端服务器通信?

    我将 apache 服务器配置为反向代理 如果我将后端服务器指定为 HTTP 则它可以正常工作 那是 我将虚拟主机 443 配置为 ProxyPass primary store http localhost 9763 store Prox
  • Python 单行代码

    我想要用 Python 编写以下代码的单行解决方案 但是如何实现呢 total 0 for ob in self oblist total sum v amount for v in ob anoutherob 它返回总价值 我想要它是单行
  • 如何从复选框数组中保存布尔状态并在使用 SharedPreferences 加载适配器时加载其状态

    我有一个用于列表视图的 CustomAdapter 我需要使用 SharedPreferences 保存布尔数组中的所有复选框状态 我想将技巧的名称 字符串数组 保存为键和每个技巧的状态 我想到的 SharedPreferences 示例