我有一个编辑文本,我希望当用户输入他的名字时,例如,当他插入他的名字时,提示永久更改。我应该在onCreate上这样做吗?如果是的话,我应该做类似if(name.isEmpty())?
<com.google.android.material.textfield.TextInputLayout
android:id="@+id/hintguy"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="2"
android:textColorHint="#ffffff"
app:errorEnabled="true">
<com.google.android.material.textfield.TextInputEditText
android:id="@+id/texto"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:backgroundTint="#4249ff"
android:hint="@string/BtnO"
android:textColor="#ffffff" />
</com.google.android.material.textfield.TextInputLayout>
<Button
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1"
android:onClick="confirmInput"
android:text="@string/Btns" />
这是我的Java代码
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
prefs= getSharedPreferences("my_data",MODE_PRIVATE);
String name = prefs.getString("MY_NAME","name");
String home = prefs.getString("MY_HOME","home");
nameInput =(EditText)findViewById(R.id.texto);
homeInput =(EditText)findViewById(R.id.textd);
Toast.makeText(this,name,Toast.LENGTH_LONG).show();
}
public void copy(View view) {
}
public void confirmInput(View view) {
String name=nameInput.getText().toString();
SharedPreferences.Editor editor = prefs.edit();
editor.putString("MY_NAME",name);
editor.apply();
Toast.makeText(this,name,Toast.LENGTH_LONG).show();
TextInputLayout textInputLayout = (TextInputLayout)findViewById(R.id.hintguy);
textInputLayout.setHint("Hello");
}
答案 0 :(得分:0)
将此内容放入onCreate中。您需要在设置提示之前检查偏好设置中是否有名称。
TextInputLayout textInputLayout = (TextInputLayout)findViewById(R.id.hintguy);
String savedName=prefs.getString("MY_NAME","");
if (savedName.length()>0){
textInputLayout.setHint("Hello "+name);
}else{
textInputLayout.setHint("hint when no name present");
}
如果在共享首选项的“ MY_NAME”键下找到了某些内容,则将在提示中进行设置。否则,您会得到随机提示。选中此link。试试吧,我希望它能起作用