我正在构建一个应用程序,如果用户输入" o"或者" O"在编辑文本的开头,应执行以下操作:
替换输入的" o"或" O"与" P"在运行时在EditText中并将TextView设置为" ORANGE"。
同样,如果用户输入" g"或" G"然后输入" g"或" G"应该替换为" P"在EditText的运行时,将TextView设置为" Green"。 等等.... 我怎么能完成这个。我使用TextWatcher()但无法实现目标。帮助将受到赞赏
package com.example.answer;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
public class data extends Activity implements OnClickListener {
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
}
Button start, startFor;
EditText sendET;
TextView gotAnswer, result;
int flag = 1;
TextWatcher tt = null;
int i = 0;
@Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
initialize();
final EditText sendET = (EditText) findViewById(R.id.sendet);
final TextView result = (TextView) findViewById(R.id.tv);
tt = new TextWatcher() {
public void afterTextChanged(Editable s) {
sendET.setSelection(s.length());
}
public void beforeTextChanged(CharSequence s, int start, int count,
int after) {
}
public void onTextChanged(CharSequence s, int start, int before,
int count) {
if (sendET.getText().toString() == "o") {
flag = 0;
}
sendET.removeTextChangedListener(tt);
if (flag == 0) {
sendET.setText(sendET.getText().toString()
.replaceAll("o", "P"));
result.setText("ORANGE");
}
sendET.addTextChangedListener(tt);
}
};
sendET.addTextChangedListener(tt);
}
private void initialize() {
start = (Button) findViewById(R.id.button1);
sendET = (EditText) findViewById(R.id.sendet);
start.setOnClickListener(this);
}
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
switch (v.getId()) {
case R.id.button1:
String bread = sendET.getText().toString();
result = (TextView) findViewById(R.id.tv);
result.setText(bread);
/*
* Bundle basket = new Bundle(); basket.putString("key", bread);
* Intent a = new Intent(data.this, openedclass.class);
* a.putExtras(basket); startActivity(a); break;
*/
}
}
}
答案 0 :(得分:0)
if (sendET.getText().toString() == "o")
这是错误的。这不是你如何检查Java中的字符串相等性。正确用法:
if(sendET.getText().toString().equals("o"))
此外,您删除了侦听器并再次添加。我不知道你的app逻辑,但我想你不想要addTextChangedListener
:
public void onTextChanged(CharSequence s, int start, int before,
int count) {
if (sendET.getText().toString() == "o") {
flag = 0;
}
sendET.removeTextChangedListener(tt); // REMOVING
if (flag == 0) {
sendET.setText(sendET.getText().toString()
.replaceAll("o", "P"));
result.setText("ORANGE");
}
sendET.addTextChangedListener(tt); // ADDING AGAIN
}