Skip to content

Instantly share code, notes, and snippets.

@LeoAndo
Last active September 30, 2023 09:30
Show Gist options
  • Save LeoAndo/6032d52c98f8a31ae74ded4115760482 to your computer and use it in GitHub Desktop.
Save LeoAndo/6032d52c98f8a31ae74ded4115760482 to your computer and use it in GitHub Desktop.
[Android] TextWatcherを使った複数Viewの表示制御
package xxx; // TODO change your package name.
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.View;
import androidx.annotation.NonNull;
import java.util.Arrays;
public final class AppTextWatcher implements TextWatcher {
@NonNull
private final Type mType;
@NonNull
private final View[] mViews;
public AppTextWatcher(
final @NonNull View... views
) {
this(Type.ENABLED, views);
}
public AppTextWatcher(
final @NonNull Type type,
final @NonNull View... views) {
this.mType = type;
this.mViews = views;
}
@Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
@Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
}
@Override
public void afterTextChanged(Editable s) {
final boolean flag = !TextUtils.isEmpty(s);
Arrays.stream(mViews).forEach(view -> {
switch (mType) {
case ENABLED:
view.setEnabled(flag);
break;
case VISIBILITY_INVISIBLE:
view.setVisibility(flag ? View.VISIBLE : View.INVISIBLE);
break;
case VISIBILITY_GONE:
view.setVisibility(flag ? View.VISIBLE : View.GONE);
break;
case CLICKABLE:
view.setClickable(flag);
break;
}
});
}
public enum Type {
ENABLED, VISIBILITY_INVISIBLE, VISIBILITY_GONE, CLICKABLE
}
}
@LeoAndo
Copy link
Author

LeoAndo commented Jul 21, 2023

Usage 1: default

        final EditText editText = findViewById(R.id.editTextText);
        final Button button = findViewById(R.id.button);
        final Switch switch1 = findViewById(R.id.switch1);
        final CheckBox checkBox = findViewById(R.id.checkBox);
        editText.addTextChangedListener(new AppTextWatcher(button, switch1, checkBox));

API 30

device-2023-07-22-005751.webm

@LeoAndo
Copy link
Author

LeoAndo commented Jul 21, 2023

Usage 2: specific Type

        final EditText editText = findViewById(R.id.editTextText);
        final Button button = findViewById(R.id.button);
        final Switch switch1 = findViewById(R.id.switch1);
        final CheckBox checkBox = findViewById(R.id.checkBox);
        editText.addTextChangedListener(
                new AppTextWatcher(
                        AppTextWatcher.Type.VISIBILITY_GONE,
                        button, switch1, checkBox
                )
        );

API 30

device-2023-07-22-010153.webm

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment