使用 setOnLongClickListener 在多个按钮上设置文本

问题描述

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

我想我已经尝试了这个线程上的所有内容setonlongclicklistener for several buttons at once

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

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.button1R.id.button2 等。