This is the question.
(1)__ is also a star.(2)__ revolves around the Sun.
edittext1: _______ edittext2: _______
So in the first blank, I am showing what the user type in edit text. If he types Sun,then the output will be like below.
(1)_Sun_is also a star.(2)__ revolves around the Sun.
edittext1: Sun edittext2: _______
So for (1) I am replacing "__" with my edit text value,as above. How to do it with (2). I tried the same logic with (2) but it replaces the first value also.
(1)Planets is also a star.(2)Planets revolves around the Sun.
edittext1: Sun
edittext2: Planets
public class MainActivity extends AppCompatActivity {
EditText ed1,ed2,ed3;
String edtv1,edtv2;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ed1= (EditText) findViewById(R.id.editText);
ed2= (EditText) findViewById(R.id.editText2);
ed3= (EditText) findViewById(R.id.editText3);
final TextView tv = (TextView) findViewById(R.id.textView);
final String sentence = tv.getText().toString();
if (ed1 != null) {
ed1.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) {
tv.setText(String.format("%s_", sentence.replace("__", "_" + s.toString())));
}
});
edtv1 = ed1.getText().toString();
}
if (ed2 != null) {
ed2.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) {
tv.setText(String.format("%s_", sentence.replace("__", "_" + s.toString())));
}
});
edtv2 = ed2.getText().toString();
}
}
}
The above is the full code.
You can use function below:
String s = "1 abc 1 def";
Log.e("Test", replace(s, "1", "1test", "2test")); --> value: 1test abc 2test def
// fuction to replace
private String replace(String source, String toReplace, String... replacements) {
StringBuilder stringBuilder = new StringBuilder(source);
int startIndex = 0;
for (int i = 0; i < replacements.length; i++) {
int index = stringBuilder.indexOf(toReplace, startIndex);
if (startIndex < 0) {
break;
}
stringBuilder.replace(index, index + toReplace.length(), replacements[i]);
startIndex = index + replacements.length;
}
return stringBuilder.toString();
}