2014-03-25 46 views
0

作爲我的應用程序的一部分,我正在嘗試創建一個可自定義的清單。用戶可以從缺省清單中選擇儘可能多的數據,並將刪除新項目的anad添加到列表中。但是,一旦列表中的項目由用戶完成,列表需要保存下次使用該應用程序的時間。保存動態創建的多個複選框的偏好android

我已經嘗試了幾種方法,其中沒有任何方法可行。有人可以幫助我嗎? 下面是代碼:

public class Dynamo extends Activity{ 
@Overrided 
protected void onCreate(Bundle savedInstanceState) { 
    // TODO Auto-generated method stub 
    super.onCreate(savedInstanceState); 

    String[] A = new String[100]; 
    String[] B = new String[100]; 
    final CheckBox[] cbx = new CheckBox[100]; 
    int i,k,j,m,q; 
    final int n; 

    ScrollView sv = new ScrollView(this); 
    final LinearLayout ll = new LinearLayout(this); 
    ll.setOrientation(LinearLayout.VERTICAL); 
    sv.addView(ll); 

    Bundle extras = getIntent().getExtras(); 
    if (extras != null) { 
     A = extras.getStringArray("var"); 
     i = extras.getInt("var2"); 
     B = extras.getStringArray("var3"); 
     k = extras.getInt("var4"); 

     for(j=0;j<i;j++) 
     { 
      cbx[j] = new CheckBox(this); 
      ll.addView(cbx[j]); 
      cbx[j].setText(A[j]); 
     } 
     for (m=0;m<k;m++) 
     { 
      cbx[m] = new CheckBox(this); 
      ll.addView(cbx[m]); 
      cbx[m].setText(B[m]); 
     } 
     n=j+m; 

     Button delete=new Button(this); 
     delete.setText("Delete"); 
     ll.addView(delete); 

     delete.setOnClickListener(new View.OnClickListener() { 
     public void onClick(View v) { 
      for(int p = 0; p < n; p++) { 
       if (cbx[p].isChecked()) 
       { 
        ll.removeView(cbx[p]); 
        Toast.makeText(getApplicationContext(), "Removing! " , Toast.LENGTH_SHORT).show(); 
       } 
      } 
     }}); 
     this.setContentView(sv); 
}  
+0

現在維捷如何?你能幫我現在嗎? – userstack

+0

我不太擅長以編程方式生成的控件。我也不明白代碼需要做這樣的事情...... –

回答

0

你應該在XML爲consitancy列表....

私人無效保存(){ SharedPreferences sharedPreferences = PreferenceManager

.getDefaultSharedPreferences(this); 

    Editor editor = sharedPreferences.edit(); 

    editor.commit(); 

//you will need the following line for each checkbox you want to save data for. 
     editor.putBoolean("CHECKBOX", yourcheckbox.isChecked(); 
     editor.commit(); 



    Toast.makeText(getBaseContext(), "Data Saved...", Toast.LENGTH_SHORT).show(); 

} 

還你需要使用這種方法加載它們,在onCreate()中調用它,但在初始化複選框後,複選框

private void loadSavedPrefs() { 
     SharedPreferences sharedPreferences = PreferenceManager 

     .getDefaultSharedPreferences(this); 

     yourcheckbox.isChecked=sharedPreferences.getBoolean("CHECKBOX", false); 

    } 
+0

如果你想讓你的列表變成動態的,你需要一個ArrayList適配器,你需要實現它。 – La5t5tarfighter

+0

那麼,我可以生成,添加和刪除列表,而不需要陣列適配器。這是列表中剩下的最後一個功能。我沒有太多時間重新使用陣列適配器重新做所有事情。你能否提供一個解決方案,而不使用XML或數組適配器? – userstack

+0

上面的調用應該工作,只要你不使用它們,直到你的項目被創建。所以在你創建它們之後,我假設在oncreate中,爲它們分配每個id,然後loadPreferences,然後將偏好保存在onPause中。 – La5t5tarfighter