我使用的是predefined button
,生成new buttons
点击它的时候。 产生新的按钮后,我想change their label
对我使用EditText
在对话框中定义其弹出onLongClick
新产生的按钮。 存储所有生成的按钮和他们的标签我使用Shared preferences
。 但问题是,重新启动后,所有生成的按钮对他们相同的标签。
code in mainactivity-----
SharedPreferences prefs=null;
String key;
int btncount = 15;
code in onCreate method----
prefs = PreferenceManager.getDefaultSharedPreferences(this);
btncount=prefs.getInt("count", 0);
LinearLayout ll = (LinearLayout)findViewById(R.id.layout1);
for(int i=0;i<btncount;i++)
{
LayoutParams lp = new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
final Button myButton = new Button(this);
myButton.getId();
myButton.setText(prefs.getString(key+myButton.getId(),"New"));
myButton.setOnLongClickListener(new OnLongClickListener() {
public boolean onLongClick(View arg0)
{
AlertDialog lbldialog = new AlertDialog.Builder(context).create();
final EditText input = new EditText(MainActivity.this);
lbldialog.setView(input);
lbldialog.setButton(DialogInterface.BUTTON_POSITIVE, "Change", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which)
{
myButton.setText(input.getText());
Editor edit = prefs.edit();
edit.putString(key+myButton.getId(), myButton.getText().toString());
edit.commit();
}
});
lbldialog.show();
return true;
}
});
ll.addView(myButton, lp);}
Code to create button-----
if(v == btnaddnew)
{
final Button btn1 = new Button(this);
btn1.setText("New");
btn1.setId(btncount);
btn1.setOnClickListener(new OnClickListener () {
@Override
public void onClick(View v){
reportDialog(btn1.getText().toString());
}
});
btn1.setOnLongClickListener(new OnLongClickListener() {
public boolean onLongClick(View arg0) {
AlertDialog lbldialog = new AlertDialog.Builder(context).create();
final EditText input = new EditText(MainActivity.this);
lbldialog.setView(input);
lbldialog.setButton(DialogInterface.BUTTON_POSITIVE, "Change",
new DialogInterface.OnClickListener()
{
public void onClick(DialogInterface dialog, int which)
{
btn1.setText(input.getText());
Editor edit = prefs.edit();
edit.putString(key+btn1.getId(), btn1.getText().toString());
edit.commit();
}
});
lbldialog.show();
return true;
}
});
LinearLayout ll = (LinearLayout)findViewById(R.id.layout1);
LayoutParams lp = new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
ll.addView(btn1, lp);
btncount++;
Editor editor = prefs.edit();
editor.putInt("count", btncount);
editor.commit();
}
检查一次,请为我提供适当的修改,因为我是新来的Android和我没有那么多的知识