假设我在一个活动中有一个EditText
视图。输入后,我想修改EditText
中的文本。例如,将"Andrew"
放入EditText
后,它将自动将文本更改为"Mr. Andrew"
。这可能吗?
答案 0 :(得分:0)
将addTextChangedListener
添加到您的EditText中,并像下面这样覆盖void SetSail()
{
promptText.text = "";
promptText2.text = "";
addParents();
if (whichSide == "sailing" && direction == "toFinish")
{
speed = 0.05f;
gameObject.transform.Translate(speed, 0, 0);
}
else if (whichSide == "sailing" && direction == "toStart")
{
speed = -0.05f;
gameObject.transform.Translate(speed, 0, 0);
}
else if (whichSide == "start" || whichSide == "finish")
{
gameObject.transform.Translate(speed, 0, 0);
removeParents();
}
}
void addParents()
{
foreach(string o in boatList)
{
GameObject obj = GameObject.Find(o);
obj.GetComponent<Rigidbody>().useGravity = false;
obj.GetComponent<Rigidbody>().isKinematic = true;
if (obj.name == "FARMER") { obj.transform.parent = playerGuide.transform; }
else {obj.transform.parent = itemGuide.transform; }
}
}
void removeParents()
{
foreach (string o in boatList)
{
GameObject obj = GameObject.Find(o);
obj.GetComponent<Rigidbody>().useGravity = true;
if(obj.name != "FARMER") {obj.GetComponent<Rigidbody>().isKinematic = false; }
obj.transform.parent = null;
}
}
afterTextChange()
答案 1 :(得分:0)
您可以尝试使用TextWatcher
来监听EditText
中的更改。但是,如the documentation所述
从此回调中对s进行进一步更改是合理的,但请注意不要陷入无限循环,因为您进行的任何更改都将导致递归再次调用此方法。
仅添加字符串将是触发StackOverflowError
的肯定方法,因为onAfterTextChanged()
将在无限循环中递归调用。
因此,您需要检查文本是否已经以要添加的字符串开头,并且仅在文本不存在的情况下才添加。这样的事情可能会起作用:
EditText myEditText = (EditText) findViewById(R.id.my_edittext);
myEditText.addTextChangedListener(new TextWatcher() {
@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) {
String prefix = "Mr. ";
String text = s.toString();
if( text.length() < prefix.length() || !text.substring(0, prefix.length()).equals(prefix) )
s.insert(0, prefix);
}
});