2016-07-28 10 views
2

このマルチセレクトリストビューは初めてです。チェックボックスのチェック状態をlistviewに保存して、ユーザーがアプリケーションを閉じてからもう一度開くと、選択したチェックボックスが選択されたままになるようにします。これを行う方法はありますか?私はそれを探して、それがSharedPreferenceを使用して行うことができることがわかったが、私はそれを使用する方法についての詳細情報を取得していない。おかげで、リスト項目の複数選択リストビューのチェックボックスのチェック状態を保存します

public class MainActivity extends AppCompatActivity { 

    ListView myList; 
    Button getChoice; 

    String[] listContent = { 

      "January", 
      "February", 
      "March", 
      "April", 
      "May", 
      "June", 
      "July", 
      "August", 
      "September", 
      "October", 
      "November", 
      "December" 

    }; 

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

     myList = (ListView)findViewById(R.id.list); 
     getChoice = (Button)findViewById(R.id.getchoice); 

     ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_multiple_choice, listContent); 
     myList.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE); 

     myList.setAdapter(adapter); 

     getChoice.setOnClickListener(new View.OnClickListener() { 
      @Override 
      public void onClick(View view) { 
       String selected = ""; 
       int cntChoice = myList.getCount(); 

       SparseBooleanArray sparseBooleanArray = myList.getCheckedItemPositions(); 
       for(int i = 0; i < cntChoice; i++){ 
        if(sparseBooleanArray.get(i)) { 
         selected += myList.getItemAtPosition(i).toString() + "\n"; 

        } 

       } 

       Toast.makeText(MainActivity.this, selected, Toast.LENGTH_LONG).show(); 

      } 
     }); 



    } 
} 

答えて

1

この方法を試してみてください。

だからあなたonCreateonDestroy方法は次のようになります: `ここAppListOfAllApps`何

SharedPreferences sharedPreferences = getSharedPreferences("MySharedPrefs", MODE_PRIVATE); 

@Override 
protected void onCreate(final Bundle savedInstanceState) { 
    ... 
    Set<String> checkedItemsSource = sharedPreferences.getStringSet("checked_items", new HashSet<String>()); 
    SparseBooleanArray checkedItems = convertToCheckedItems(checkedItemsSource); 
    for (int i = 0; i < checkedItems.size(); i++) { 
     int checkedPosition = checkedItems.keyAt(i); 
     listView.setItemChecked(checkedPosition, true); 
    } 
} 

@Override 
protected void onDestroy() { 
    super.onDestroy(); 
    SparseBooleanArray checkedItems = listView.getCheckedItemPositions(); 
    Set<String> stringSet = convertToStringSet(checkedItems); 
    sharedPreferences.edit() 
      .putStringSet("checked_items", stringSet) 
      .apply(); 
} 

private SparseBooleanArray convertToCheckedItems(Set<String> checkedItems) { 
    SparseBooleanArray array = new SparseBooleanArray(); 
    for(String itemPositionStr : checkedItems) { 
     int position = Integer.parseInt(itemPositionStr); 
     array.put(position, true); 
    } 

    return array; 
} 

private Set<String> convertToStringSet(SparseBooleanArray checkedItems) { 
    Set<String> result = new HashSet<>(); 
    for (int i = 0; i < checkedItems.size(); i++) { 
     result.add(String.valueOf(checkedItems.keyAt(i))); 
    } 

    return result; 
} 
+0

私のアプリケーションであなたのコードを実行すると、アプリケーションは 'SharedPreferences sharedPreferences = getSharedPreference'行のNPEでクラッシュする@Michael – CodeAssasins

+0

とにかくそれを解決しました。ところで、あなたのコードは最高の人間です。 @マイケル。 – CodeAssasins

+0

また、このsharedpreferenceを削除する方法はありますか? – CodeAssasins

0

はあなたのチェックボックスは、この

listView.setOnItemClickListener(new OnItemClickListener() 
     { 
      public void onItemClick(AdapterView<?> parent, View view, int position, long id) 
      { 
       AppListOfAllApps hideSelectedApps = (AppListOfAllApps) parent.getItemAtPosition(position); 
       if (view != null) 
       { 
        CheckBox checkBox = (CheckBox) view.findViewById(R.id.checkBox1); 
        hideSelectedApps = (AppListOfAllApps) checkBox.getTag(); 
        hideSelectedApps.setSelected(!checkBox.isChecked()); 
        checkBox.setChecked(!checkBox.isChecked()); 
       } 
      } 
     }); 

ストアのようsharedprefrenceで選択した項目を確認した後、ボタン上の共有に保存されているリスト項目内のすべての存在の項目間の比較ですが作るヒットその後、ちょうどこの

を行い、この

boolean chkbox = false; 
     String selecteditem = SharedPreferences.getSharedPref(getApplicationContext()).selecteditem(); 

ようprefrence

は今、このチェックボックスの状態を保存し、また、あなたのモデル内の状態を維持するために必要とするため、それ

+0

? SharedPreferenceで選択した項目を保存する方法は? – CodeAssasins

+0

申し訳ありません私は自分のコードを追加しました。私は何をしたいのですか?appslistofallappsはurアダプタ内のallitemsです.......選択した項目をキー値のペアで保存します – tanmeet

0

をretrivesコンストラクタ をアダプタためにこれを渡します。また、onBindViewコールごとにモデルごとのステータスをリセットするだけです。あなたからの助けを取ることができます詳細について -

https://stackoverflow.com/a/38182528/1741586

は、それはあなたを助けることを願っています:)

+0

私はlistviewを使用しています。では、ここでlistviewでモデルクラスを使う方法は? @Neo – CodeAssasins

+0

そのシンプルなだけですべてのデータを持つモデルを作る、あなたは行が必要です。 getViewでは、モデルごとにチェックボックスを更新するだけです。そして、モデルtoooのcheckbox chngeの状態変更について。 – Neo

+0

試してみてください!問題を解決できない場合は、私に教えてください。私は助けてくれるでしょう:) – Neo

0

あなたが選択した値のブール配列を維持するために、次にあなたがsharedpreferenceに保管することができます必要なすべてのファーストとあなたもまたチェックし、そのためのカスタムアダプタを必要とするMultiple Checkbox values in listview storing & retrieving using sharedpreferences

活動

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



    String[] listArray = new String[] { //Add String values }; 
    SharedPreferences sharedPreferences = getSharedPreferences("status", MODE_PRIVATE); 

    Boolean[] checkedStatus = new Boolean[listArray.length]; 
    for (int index = 0; index < checkedStatus.length; index++) 
     checkedStatus[index] = sharedPreferences.getBoolean(Integer.toString(index), false); 

    ListView listView = (ListView) findViewById(R.id.listview); 
    CustomAdapter adapter = new CustomAdapter(this, R.layout.row_layout, listArray, checkedStatus); 
    listView.setAdapter(adapter); 
} 

はあなたがSharedPreferencesで、例えば、状態を保存することができます

public class CustomAdapter extends ArrayAdapter<String> implements CompoundButton.OnCheckedChangeListener{ 

String[] values; 
Boolean[] checkedStatus; 

public CustomAdapter(Context context, int resource, String[] values, Boolean[] checkedStatus) { 
    super(context, resource, values); 

    this.values = values; 
    this.checkedStatus = checkedStatus; 
} 

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

@Override 
public String getItem(int position) { 
    return values[position]; 
} 

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

@Override 
public View getView(int position, View convertView, ViewGroup parent) { 
    View view = convertView; 
    if(view == null){ 
     LayoutInflater inflater = (LayoutInflater) getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE); 
     view = inflater.inflate(R.layout.row_layout, null); 
    } 

    TextView textView = (TextView) view.findViewById(R.id.title); 
    textView.setText(values[position]); 

    CheckBox box = (CheckBox) view.findViewById(R.id.chk); 
    box.setTag(position); 
    box.setOnCheckedChangeListener(this); 
    box.setChecked(checkedStatus[position]); 

    return view; 
} 

@Override 
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) { 
    Integer index = (Integer) buttonView.getTag(); 
    checkedStatus[index] = isChecked; 
    String key = index.toString(); 

    SharedPreferences sharedPreferences=getContext().getSharedPreferences("status", Context.MODE_PRIVATE); 
    SharedPreferences.Editor editor=sharedPreferences.edit(); 
    editor.putBoolean(key,isChecked); 
    editor.apply(); 
} 
+0

私はあなたの方法を試しましたが、アクティビティでブール値[]を求めました。それのための選択肢はありますか? @Aditya Vyas – CodeAssasins

+0

次にアクティビティでブール値を作成する –

関連する問題