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

Posted

技术标签:

【中文标题】如何从复选框数组中保存布尔状态并在使用 SharedPreferences 加载适配器时加载它们的状态【英文标题】:How to save boolean states from an array of checkboxes and load their states when the adapter is loaded using SharedPreferences 【发布时间】:2018-07-11 04:40:40 【问题描述】:

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

我想到的 SharedPreferences 示例:

("诡计名称", false/true) (“ATW - 环游世界”,假/真)

每次用户更改任何需要在 SharedPreference 中更新的状态以获取点击的技巧。

我尝试了以下两种方法进行测试,但没有成功,我不知道如何使这个工作。

storeArray() 和 loadArray()。

listview with the checkboxes

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);
                

            );

    


【问题讨论】:

从您的另一篇文章中,我知道您有 4 个列表。您要保存所有 4 个列表的状态还是只保存当前活动的一个? 谢谢。我用新信息更新了我的帖子,并添加了包含列表视图中项目的活动。是的,它有四个列表(lower、upper、sitdown、combosfamosos)。 【参考方案1】:

试试这个适配器代码:

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();
    

希望有帮助!

【讨论】:

天啊!!!你救了我,非常感谢!不知道设置适配器的时候可以调用方法。 你可以看看我在ListView上的博客:programandroidlistview.blogspot.com,它会给你一个比许多教程更完整的ListView图片。

以上是关于如何从复选框数组中保存布尔状态并在使用 SharedPreferences 加载适配器时加载它们的状态的主要内容,如果未能解决你的问题,请参考以下文章

保存和加载布尔状态

在sqlite android中存储布尔值

如何正确更改从数据库中提取的复选框的状态

flex 3 数据网格:如果 == 0 则隐藏值并在布尔值上显示复选框

我们如何在 SwiftUi 的另一个视图中传递布尔状态

从角度表单复选框保存布尔真/假并将其保存到 Oracle 等后端数据库的正确方法是啥? [关闭]