问题描述
我正在Android应用程序注册页面中使用材料设计。我在xml文件中使用了以下代码。
XML文件
<com.google.android.material.textfield.TextInputLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="@+id/regEmailId"
android:hint="Email Id"
style="@style/Widget.MaterialComponents.TextInputLayout.OutlinedBox">
<com.google.android.material.textfield.TextInputEditText
android:layout_width="match_parent"
android:layout_height="wrap_content"/>
</com.google.android.material.textfield.TextInputLayout>
上面的xml是从线性布局内部呈现的。
TextInputLayout regMailId = findViewById(R.id.regEmailId);
Editable regEmail = regMailId.getEditText().getText();
我遵循了这篇here SO文章中给出的选项。尽管答案表明我应该使用
String text = textInputLayout.getEditText().getText();
Change variable text type to editable
Migrate text type to editable
Wrap using String.valueOf()
如果我使用的字符串值包装
String text = String.valueOf( regMailId.getEditText().getText() );
我没有得到可变文本的输出。
当我将其更改为
Editable regEmail = regMailId.getEditText().getText();
我可以烘烤输入的文本,但是我无法获得实际的文本来对它们进行任何验证。例如,在password
和confirmpassword
字段中,虽然可以看到值被烘烤,但我无法比较。
java.lang.String.android.text.SpannableStringBuilder
我尝试使用toString(),getText()。toString()等将字符串提取到regEmail。什么都没有。
如何在材料设计布局中获取textinput字段的字符串。
以下是我的应用程序gradle:
apply plugin: 'com.android.application'
android {
compileSdkVersion 29
defaultConfig {
applicationId "com.example.telescope"
minSdkVersion 16
targetSdkVersion 29
versionCode 1
versionName "1.0"
multiDexEnabled true
testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
}
compileOptions {
sourceCompatibility JavaVersion.VERSION_1_8
targetCompatibility JavaVersion.VERSION_1_8
}
buildTypes {
release {
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'),'proguard-rules.pro'
}
}
}
dependencies {
implementation filetree(dir: "libs",include: ["*.jar"])
implementation 'androidx.appcompat:appcompat:1.2.0'
implementation 'androidx.constraintlayout:constraintlayout:1.1.3'
testImplementation 'junit:junit:4.12'
androidTestImplementation 'androidx.test.ext:junit:1.1.1'
androidTestImplementation 'androidx.test.espresso:espresso-core:3.2.0'
implementation 'com.google.android.material:material:1.2.0'
implementation 'com.android.support:multidex:2.0.0'
implementation 'com.amplifyframework:core:1.1.2'
implementation 'com.amplifyframework:aws-datastore:1.1.2'
implementation 'com.amplifyframework:aws-api:1.1.2'
implementation 'com.amplifyframework:aws-auth-cognito:1.3.0'
}
解决方法
要获取“实时”文本,应将TextChangeListener添加到EditText对象:
TextInputLayout regMailId = findViewById(R.id.regEmailId);
regEmailId.getEditText().addTextChangedListener(new TextWatcher() {
public void afterTextChanged(Editable s) {}
public void beforeTextChanged(CharSequence s,int start,int count,int after) {}
public void onTextChanged(CharSequence s,int before,int count) {
//get the String from CharSequence with s.toString() and process it to validation
}
});