在Android中使用SharedPreference存储动态按钮标签时出错?

时间:2014-02-24 11:49:18

标签: android xml android-layout button sharedpreferences

在我的应用程序中,我正在使用Predefined ButtonDynamically Generate Button。使用标签创建的按钮为Test1,Test2,Test 3等。但在重新启动应用程序后,所有Dynamically generated Buttons都有"New"作为其标签。  添加按钮的代码:

AlertDialog.Builder addreport = new AlertDialog.Builder(MainActivity.this);
        addreport.setTitle("Add New Button");
        LinearLayout addlayout = new LinearLayout(MainActivity.this);
        addlayout.setOrientation(LinearLayout.VERTICAL);
        addlayout.setPadding(15,15,15,15);

        final EditText btnlabel = new EditText(MainActivity.this);
        btnlabel.setHint("Enter btn label");
        addlayout.addView(btnlabel);

        addreport.setView(addlayout);
        addreport.setNeutralButton("SUBMIT", new DialogInterface.OnClickListener() {

            @Override
            public void onClick(DialogInterface dialog, int which) {

                    LinearLayout ll = (LinearLayout)findViewById(R.id.layout1);

                    //final Button btn = new Button(MainActivity.this);
                    btn.setText(btnlabel.getText());
                    btn.setId(i);
                    LayoutParams lp = new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT);       
                    ll.addView(btn, lp);
                    i++;
                    btncount++;
                    Editor edit = preferences.edit();
                    edit.putString("btn"+btn.getId(), btn.getText().toString());
                    edit.putInt("count", btncount);
                    edit.commit();
                    return; 
                    }
            });
        AlertDialog adrptdialog = addreport.create();
        adrptdialog.show();
    }   
    }

SharedPreference存储代码:

preferences = getSharedPreferences(PREFS_NAME, MODE_PRIVATE);
    //btncount = preferences.getInt("count", 0);
    String labels = preferences.getString("btn"+btn.getId(), "New");
    for( i=0;i<btncount;i++)
    {
        final Button btn1 = new Button(this);
        btn1.setId(i);
        LinearLayout ll = (LinearLayout)findViewById(R.id.layout1);
        LayoutParams lp = new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);       
        btn1.setText(labels);
    ll.addView(btn1, lp);   
    }   

1 个答案:

答案 0 :(得分:0)

preferences = getSharedPreferences(PREFS_NAME, MODE_PRIVATE);
int btncount = preferences.getInt("count", 0);
LinearLayout ll = (LinearLayout)findViewById(R.id.layout1);
for( i=0;i<btncount;i++)
{
    String label = preferences.getString("btn"+i, "New");
    Button btn1 = new Button(this);
    btn1.setId(i);
    LayoutParams lp = new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);       
    btn1.setText(label);
    ll.addView(btn1, lp);   
}