I want to access external variables from Android’s onClick.

Android

When writing the process for when a button is clicked using the OnClickListener, there are different approaches and preferences.

However, I personally don’t use the method of implementing listeners or preparing a separate OnClickListener for each button (because I dislike the scattering of code).

I prefer to implement it by directly passing an anonymous class to setOnClickListener(), as shown below.

findViewById(R.id.save_bt).setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View v) {
        // The process when clicked.
    }
});


However, variables outside the anonymous class cannot be scoped from within onClick.

// I want to use this variable inside onClick.
int id = 1;

findViewById(R.id.save_bt).setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View v) {
        update(id); // The variable 'id' cannot be scoped.
    }
});

I don’t want to bother making the ‘id’ variable a member variable, and extending it seems cumbersome. Is there any way to pass the value while keeping this form?


In conclusion, I’ll implement a custom method and member in the anonymous class.
Like this.

// I want to use this variable inside onClick.
int id = 1;

findViewById(R.id.save_bt).setOnClickListener(new View.OnClickListener() {
    private int id;
    @Override
    public void onClick(View v) {
        // Click processing.
        update(id);
    }
    public View.OnClickListener setId(int id) {
        this.id = id;
        return this;
    }
}.setId(id));

If there’s a simpler and more elegant way, I’d love to know. Since I’ve never done team development with Android, I’m not too familiar with the best practices.

Maybe it can be done more effectively with Kotlin.

タイトルとURLをコピーしました