2014-02-05 29 views
1

動態生成按鈕並使用共享首選項存儲它們。創建按鈕後,使用EditText更改其標籤並將按鈕標籤設置爲myButton.setText(input.getText());。還使用另一個Shared Preference to store their label。 代碼來創建按鈕:使用按鈕,保存標籤動態生成的按鈕具有相同的標籤?

final Button btn1 = new Button(this); 
     btn1.setText("New"); 
     btn1.getId();  
     btn1.setOnClickListener(this); 
     btn1.setOnClickListener(new OnClickListener() { 
      @Override 
      public void onClick(View v){ 
       mDialog(btn1.getText().toString()); 
      } 
     }); 
LinearLayout ll = (LinearLayout)findViewById(R.id.layout1); 
     LayoutParams lp = new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);  
     ll.addView(btn1, lp); 
     count++; 
     Editor editor = prefs.edit(); 
     editor.putInt("count", count); 
     editor.commit(); 
btn1.setOnLongClickListener(new OnLongClickListener() { 
      public boolean onLongClick(View arg0) { 
final EditText input = new EditText(MainActivity.this); 
       mdialog.setView(input); 

改變

btn1.setText(input.getText()); 
         Editor edit = preference.edit(); 
         edit.putString("key",btn1.getText().toString()); 
         edit.commit(); 

代碼Shared Preference在onCreate方法

preference = PreferenceManager.getDefaultSharedPreferences(this); 
    prefs = PreferenceManager.getDefaultSharedPreferences(this); 
    count=prefs.getInt("count", 0); 
    LinearLayout ll = (LinearLayout)findViewById(R.id.layout1); 
    for(i=0;i<count;i++){ 
     LayoutParams lp = new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);  
     final Button myButton = new Button(this); 
     myButton.setOnClickListener(new OnClickListener() { 
      @Override 
      public void onClick(View v){ 
       mDialog(myButton.getText().toString()); 
      } 
     }); 
     myButton.getId(); 
     myButton.setText(preference.getString("key","New")); 
new DialogInterface.OnClickListener() { 
        public void onClick(DialogInterface dialog, int which) 
        { 
         myButton.setText(input.getText()); 
         Editor edit = preference.edit(); 
         edit.putString("key", myButton.getText().toString()); 
         edit.commit(); 
        } 
       }); 
ll.addView(myButton, lp); 
+0

你的意思是你保存的文字在首選項中總是一樣的? –

+0

,因爲你總是用同一個鑰匙保存你的價值,你需要每個標籤的唯一密鑰 –

+0

@Amrola是的,一旦我用不同的文本(衣服,配件,鞋子等)重命名所有按鈕,但重新啓動應用程序時,所有按鈕都有相同的文本)。 –

回答

0

您設置的最後一個按鈕的名稱是定義所有按鈕的名稱:

edit.putString("key",btn1.getText().toString()); 

所以你用「鑰匙」保存了所有的東西,所以你正在使用所有按鈕的最後保存的按鍵。

你可以做的是:

月1日 - 使用一個數據庫來保存按鈕的名稱。

2日 - 如果你的應用程序API大於11

使用SharedPreferences.Editor putStringSet(String key, Set<String> values) 在這裏你會得到一個鍵,多個值,這樣可以保存所有的按鈕名稱

,並請給我反饋。

希望可以幫到

+0

類型SharedPreferences.Editor中的putStringSet(String,Set )方法不適用於參數(String,String) –

+0

我是android新手,所以不知道那麼你可以幫助一段代碼 –

+0

給我時間來實現這一點。 –