【发布时间】:2014-02-05 07:14:06
【问题描述】:
动态生成按钮并使用共享首选项存储它们。创建按钮后,使用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();
在 oncreate 方法中定义的Shared Preference 的代码
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);
【问题讨论】:
-
你的意思是你保存在首选项中的文本总是一样的?
-
因为你总是用相同的键保存你的值,所以每个标签都需要唯一的键
-
@Amrola 是的,一旦我用不同的文本(服装、配饰、鞋子等)重命名所有按钮,但是当重新启动应用程序时,所有按钮都有相同的文本(鞋子)。
-
@Shayan pourvatan 如果可能的话,你能告诉我如何解决这个问题吗
-
你需要存储用于保存的最后一个 id,然后你需要 ++ 来获取另一个唯一密钥
标签: android button sharedpreferences dynamically-generated