使用setOnLongClickListener对多个按钮进行setText



我试图在setOnLongClickListener之后改变按钮上的文本,有六个按钮可供选择。目前,无论我单击哪个按钮,列表按钮都会用新的文本更新。

我想我已经尝试了这条线上的一切:一次设置多个按钮的Setonlongclicklistener

最终我希望将这些新的按钮值保存到共享首选项中,以便下次启动应用程序时它们在那里。

public class MainActivity extends AppCompatActivity {
private Button btn;
Context context;
final String[] task = new String[1];
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
context = MainActivity.this;
Resources r = getResources();
String pName = getPackageName();
String PREFERENCES_FILE_KEY = "com.example.buttondemo";
String SECURE_PREFS_FILE_KEY = "com.example.buttonnames";
// Declare shared preferences
SharedPreferences sharedPreferences = this.getSharedPreferences(PREFERENCES_FILE_KEY, Context.MODE_PRIVATE);
// get shared preferences for each button and apply the stored name to each button
//String buttonText = sharedPreferences.getString("Value01", "Button_01");
for (int i=1;i<=6;i++) {
String buttonId = "button" + i;
btn = (Button) findViewById(r.getIdentifier(buttonId, "id", pName));
btn.setOnLongClickListener(new View.OnLongClickListener() {
@Override
public boolean onLongClick(final View v) {
task[0] = showAddItemDialog(MainActivity.this, btn);
//sharedPreferences.edit().putString(buttonId, task[0]).apply();
return true;
}
});
}
}

private String showAddItemDialog(Context context, Button btnNew) {
final EditText taskEditText = new EditText(context);
taskEditText.setFilters(new InputFilter[]{new InputFilter.LengthFilter(10)});
final String[] task = new String[1];
AlertDialog dialog = new AlertDialog.Builder(context)
.setTitle("Enter New button value")
.setMessage("Enter New button value:")
.setView(taskEditText)
.setPositiveButton("Update", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
task[0] = String.valueOf(taskEditText.getText());
btnNew.setText(String.valueOf(taskEditText.getText()));
}
})
.setNegativeButton("Cancel", null)
.create();
dialog.show();
return task[0];
}
}

谢谢。

发生的事情是btn变量在循环的每次迭代中被重新分配。因此,一旦长单击侦听器触发,您将调用showAddItemDialog(this, btn),其中btn持有对上次循环迭代(当i = 6)中设置的任何内容的引用。

所以你正在经历的行为是有意义的。希望这足以给你指明正确的方向。


作为旁注,查找基于来自r.getIdentifier()的动态id的视图可能是一个糟糕的设计选择,并且可能在将来打开错误。如果可能的话,我建议将其简化为只使用R.id.button1,R.id.button2等。

最新更新