Last active
September 30, 2023 09:30
-
-
Save LeoAndo/6032d52c98f8a31ae74ded4115760482 to your computer and use it in GitHub Desktop.
[Android] TextWatcherを使った複数Viewの表示制御
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 | |
} | |
} |
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
Usage 1: default
API 30
device-2023-07-22-005751.webm