動態生成按鈕並使用共享首選項存儲它們。創建按鈕後,使用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);
你的意思是你保存的文字在首選項中總是一樣的? –
,因爲你總是用同一個鑰匙保存你的價值,你需要每個標籤的唯一密鑰 –
@Amrola是的,一旦我用不同的文本(衣服,配件,鞋子等)重命名所有按鈕,但重新啓動應用程序時,所有按鈕都有相同的文本)。 –