2012-04-23 110 views
2

如何在下次打開應用程序時使用共享首選項來存儲我的複選框的狀態?我正在使用一個自定義適配器,所以我猜它必須放在裏面,但我不太確定。使用SharedPreferences在列表視圖中存儲複選框的狀態

我的適配器:

public class MobileArrayAdapter extends ArrayAdapter<String> { 
private final Context context; 
private final String[] values; 
private ArrayList<Boolean> itemChecked = new ArrayList<Boolean>(); 


    public MobileArrayAdapter(Context context, String[] values) { 
     super(context, R.layout.list_adapter, values); 
     this.context = context; 
     this.values = values; 


     for (int i = 0; i < this.getCount(); i++) { 
      itemChecked.add(i, false); 
     } 
    } 

    @Override 
    public View getView(final int position, View convertView, 
      ViewGroup parent) { 
     View rowView = convertView; 
     if (rowView == null) { 
      LayoutInflater inflater = (LayoutInflater) context 
        .getSystemService(Context.LAYOUT_INFLATER_SERVICE); 
      rowView = inflater.inflate(R.layout.list_adapter, 
        parent, false); 
     } 
      // in your code you search for the CheckBox with the id checkBox1 2 times so I assumed that you are referring to the same view. 
     CheckBox cBox = (CheckBox) rowView.findViewById(R.id.checkBox1); 
     cBox.setTextColor(0xFFFFFFFF); 
     cBox.setText(values[position]);  
     cBox.setOnCheckedChangeListener(new OnCheckedChangeListener() { 

      public void onCheckedChanged(CompoundButton buttonView, 
        boolean isChecked) { 
       if (isChecked) { 
        itemChecked.set(position, true); 
        // do some operations here 
       } else { 
        itemChecked.set(position, false); 
        // do some operations here 
       } 
      } 
     }); 
     cBox.setChecked(itemChecked.get(position)); 
     return rowView; 
    } 

} 

我的主要活動:

public class TheKevinAndEricaBoxActivity extends Activity { 
/** Called when the activity is first created. */ 
private String[] myString; 
private String list; 
private String[] myString2; 
private String list2; 
private static final Random rgenerator = new Random(); 
private static final Random rgenerator2 = new Random(); 
MediaPlayer mp; 
final Context mContext = this; 
final Context context = this; 
private Button button; 

@Override 
public void onCreate(Bundle savedInstanceState) { 
    super.onCreate(savedInstanceState); 
    setContentView(R.layout.main); 
    Resources res = getResources(); 
    addListenerOnButton(); 




    myString = res.getStringArray(R.array.myArray); 

    list = myString[rgenerator.nextInt(myString.length)]; 

    myString2 = res.getStringArray(R.array.myArray2); 

    list2 = myString2[rgenerator.nextInt(myString2.length)]; 
} 



    public void addListenerOnButton() { 

     final Context context2 = this; 

     ImageButton ibg = (ImageButton) findViewById(R.id.buttongallery); 

     ibg.setOnClickListener(new OnClickListener() { 

      @Override 
      public void onClick(View arg0) { 

       Intent intent = new Intent(context2, App2Activity.class); 
       startActivityForResult(intent, 0); 

      } 

     }); 


    ImageButton ib = (ImageButton) findViewById(R.id.imagebutton1); 
    ib.setOnClickListener(new OnClickListener() { 
     @Override 
     public void onClick(View erica) { 
      AlertDialog.Builder b = new AlertDialog.Builder(
        TheKevinAndEricaBoxActivity.this); 
      b.setMessage(myString[rgenerator.nextInt(myString.length)]); 
      b.setTitle(R.string.title1); 
      b.setIcon(R.drawable.menuiconerica); 
      b.setPositiveButton("Back", 
        new DialogInterface.OnClickListener() { 
         @Override 
         public void onClick(DialogInterface dialog, 
           int which) { 
          dialog.cancel(); 
         } 
        }); 
      Dialog d = b.create(); 
      d.show(); 
     } 
    }); 

    ImageButton ib2 = (ImageButton) findViewById(R.id.imagebutton2); 
    ib2.setOnClickListener(new OnClickListener() { 
     @Override 
     public void onClick(View kevin) { 
      AlertDialog.Builder b = new AlertDialog.Builder(
        TheKevinAndEricaBoxActivity.this); 
      b.setMessage(myString2[rgenerator2.nextInt(myString2.length)]); 
      b.setTitle(R.string.title2); 
      b.setIcon(R.drawable.menuiconkevin); 
      b.setPositiveButton("Back", 
        new DialogInterface.OnClickListener() { 
         @Override 
         public void onClick(DialogInterface dialog, 
           int which) { 
          dialog.cancel(); 
         } 
        }); 
      Dialog d = b.create(); 
      d.show(); 

     } 
    }); 


    ImageButton Ib3 = (ImageButton) findViewById(R.id.imagebutton3); 
    Ib3.setOnClickListener(new View.OnClickListener() { 
     public void onClick(View lemonclick) { 
      mp = MediaPlayer.create(getApplicationContext(),R.raw.lemonspeech); 
      mp.start(); 


     } 
    }); 
    button = (Button) findViewById(R.id.button01); 

    // add button listener 
    button.setOnClickListener(new OnClickListener() { 

     public void onClick(View arg0) { 

     // custom dialog 
     final Dialog dialog = new Dialog(context); 
     dialog.setContentView(R.layout.list); 
     dialog.setTitle("The List"); 


     // set the custom dialog components - text, image and button 
     //TextView text = (TextView) dialog.findViewById(R.id.TextView01); 
     //text.setText("Did you not read the button? :P i'm not finshed on this yet XD"); 


     ListView listView = (ListView) findViewById(R.id.myList); 
     String[] values = new String[] { "value1", "value2", }; 


     MobileArrayAdapter mAdapter = new MobileArrayAdapter(getBaseContext(), values); 
     ListView mListView = (ListView) dialog.findViewById(R.id.myList); 
     mListView.setAdapter(mAdapter); 


     Button dialogButton = (Button) dialog.findViewById(R.id.Button01); 
     // if button is clicked, close the custom dialog 
     dialogButton.setOnClickListener(new OnClickListener() { 
      @Override 
      public void onClick(View v) { 
       dialog.dismiss(); 
      } 
     }); 

     dialog.show(); 
     } 

    }); 
    } 
} 

回答

4

OnCLickListenerButton補充一點:

//... 
// custom dialog 
final Dialog dialog = new Dialog(context); 
dialog.setContentView(R.layout.list); 
dialog.setTitle("The List"); 

prefs = PreferenceManager.getDefaultSharedPreferences(this); 
prefsEditor = prefs.edit(); 
String currentlyStored = prefs.getString("checked_list", null); 
int[] savedStatus = null; 
if (currentlyStored != null) { 
    String[] tmp = currentlyStored.split(","); 
    savedStatus = new int[tmp.length]; 
    for (int i = 0; i < tmp.length; i++) { 
     savedStatus[i] = Integer.parseInt(tmp[i]); 
    } 
} 
adapter = new MobileArrayAdapter(this, soundnames, savedStatus); 
ListView mListView = (ListView) dialog.findViewById(R.id.myList); 
mListView.setAdapter(mAdapter); 
//... 

其中:

private SharedPreferences prefs; 
private SharedPreferences.Editor prefsEditor; 
private MobileArrayAdapter adapter; 

是與ListView(在adapter領域類字段將保留您設置你的適配器對象列表)。

修改自定義適配器的構造是這樣的:

public MobileArrayAdapter(Context context, String[] values, 
       int[] oldStatus) { 
      super(context, R.layout.adapters_simpleplay_row, values); 
      this.context = context; 
      this.values = values; 

      // make every CheckBox unchecked and then loop through oldStatus(if 
      // not null) 
      for (int i = 0; i < this.getCount(); i++) { 
       itemChecked.add(i, false); 
      } 
      if (oldStatus != null) { 
       for (int j = 0; j < oldStatus.length; j++) { 
        itemChecked.set(oldStatus[j], true); 
       } 
      } 
     } 

此外,在您的自定義適配器MobileArrayAdapter添加下面的方法:

public ArrayList<Boolean> getCheckedStatus() { 
      return itemChecked; 
} 

最後聽者您dialogButton補充一點:

dialogButton.setOnClickListener(new OnClickListener() { 
      @Override 
      public void onClick(View v) { 
          String toStore = ""; 
      ArrayList<Boolean> status = adapter.getCheckedStatus(); 
      for (int i = 0; i < status.size(); i++) { 
       if (status.get(i)) { 
        toStore += i + ","; 
       } 
      } 
      prefsEditor.putString("checked_list", toStore.equals("") ? null 
        : toStore.substring(0, toStore.length() - 1)); 
      prefsEditor.commit(); 
       dialog.dismiss(); 
      } 
     }); 
+0

什麼是聲名? – CarbonAssassin 2012-04-23 18:48:20

+0

這不是保存它們:/ – CarbonAssassin 2012-04-23 18:55:04

+0

@CarbonAssassin聲名是來自自定義適配器構造函數String [] values'的String數組。我編輯了我的答案。 – Luksprog 2012-04-23 18:56:30

1

要保存選擇做一個方法saveSelections並調用它在onPause()onDestroy(),或創建一個按鈕做同樣的你... 編輯:

由於您使用的是一個ListView這是我選擇的MultipleChoice OSE你能做到這一點的onCreate ...

listView = (ListView) findViewById(R.id.list); 
     listView.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE); 
     listView.setAdapter(new ArrayAdapter<String>(this, 
       android.R.layout.simple_list_item_multiple_choice, 
       android.R.id.text1, names)); 

創建的onCreate()

private void LoadSelections() { 
     SharedPreferences sp = getPreferences(MODE_PRIVATE); 
     if (sp.contains(LOAD_LIST)) { 
      String savedItems = sp.getString(LOAD_LIST, ""); 
      this.selectedItems.addAll(Arrays.asList(savedItems.split(","))); 
      int count = this.listView.getAdapter().getCount(); 
      for (int i = 0; i < count; i++) { 
       String currentItem = (String) listView.getAdapter().getItem(i); 
       if (this.selectedItems.contains(currentItem)) { 
        this.listView.setItemChecked(i, true); 
       } 

      } 
     } 
    } 

    public void SaveSelections() { 
     SharedPreferences sp = getPreferences(MODE_PRIVATE); 
     SharedPreferences.Editor prefEditor = sp.edit(); 
     String savedItems = getSavedItems(); 
     prefEditor.putString(LOAD_LIST, savedItems); 
     prefEditor.commit(); 
    } 

    private String getSavedItems() { 
     String savedItems = ""; 
     int count = listView.getAdapter().getCount(); 
     for (int i = 0; i < count; i++) { 
      if (listView.isItemChecked(i)) { 
       if (savedItems.length() > 0) { 
        savedItems += "," + listView.getItemAtPosition(i); 
       } else { 
        savedItems += listView.getItemAtPosition(i); 
       } 
      } 
     } 
     return savedItems; 
    } 
中的onPause(

然後)外的這三種方法,這樣做:

@Override 
protected void onPause() { 
    SaveSelections(); 
    super.onPause(); 
} 

後來總算在onCreate調用這個..

LoadSelections(); 
+0

我在哪裏放置第一段代碼?並且我不需要在我的適配器的if語句中放置任何東西? – CarbonAssassin 2012-04-23 18:02:00

+0

我給了你一個抽象的想法,你可以做什麼,你將不得不做一些我在Activity中設置適配器的東西,按照這個方法,它會解決你的問題。 – 2012-04-23 18:07:15

+0

請參閱我編輯答案... – 2012-04-23 18:14:35

0

你可以製作一串0 & 1並使用共享偏好進行存儲。您使用的複選框數量(或視圖數量)將是字符串的長度。你相應地保存它。

如:

String s[]="0000000000"; 
for (i=0;i<s.length();i++) 
if (checkboxAtLocation(i)==true) //checkboxAtLocation() will return a boolean variable on basis of its checked or not 
    s[i]=1; 

現在存儲此字符串。 再次開始活動時,使用此字符串設置複選框。

這是有點複雜的實施,但根據我的知識最有效的方式。 我希望它能解決你的疑問。

+0

我最好需要所有步驟上的幫助,因爲之前從未使用共享偏好。如果你需要我把更多的代碼,我可以但我真的需要確切的植入:) – CarbonAssassin 2012-04-23 18:15:21

+0

需要寫很多的代碼。有時需要。直到你可以試試這個 - 建立一個靜態字符串s [] =「00000000」。將其更新爲getView()方法中添加的視圖。並將該字符串保存爲共享首選項。在啓動應用程序時,使用此標記複選框。評論,如果你得到它或懷疑。 – 2012-04-23 18:55:59

相關問題