why not display two picture in text? - java

When I type S in text1 a corresponding picture appears in text2 however when I type G in text1 a corresponding picture is shown in text2, but the previous picture of S is shown as a letter instead of a picture. Why is that? Why can't it display two pictures? What's wrong?
public class MainActivity extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final EditText te1 = (EditText)findViewById(R.id.t1);
final EditText te2 = (EditText)findViewById(R.id.t2);
final Button v = (Button)findViewById(R.id.b1);
v.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
//imva.setImageResource(R.id.b1);
te2.setText(" ");
String t= te1.getText().toString();
char [] aa = t.toString().toCharArray();
for (int i = 0 ; i < aa.length ; i++)
{
if (aa[i] == 's')
{
SpannableStringBuilder builder = new SpannableStringBuilder(te1.getText());
do {
ImageSpan imageSpan = new ImageSpan(getBaseContext(),R.drawable.a1);
int pos = builder.toString().indexOf("s");
builder.replace(pos, pos + 1, "$");
builder.setSpan(imageSpan, pos, pos + 1,Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
} while (builder.toString().indexOf("s") > -1);
te2.setText(builder);
}
if (aa[i] == 'g')
{
SpannableStringBuilder builder = new SpannableStringBuilder(te1.getText());
do {
ImageSpan imageSpan = new ImageSpan(getBaseContext(),R.drawable.a2);
int pos = builder.toString().indexOf("g");
builder.replace(pos, pos+ 1, "$");
builder.setSpan(imageSpan, pos, pos + 1,Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
} while (builder.toString().indexOf("g") > -1);
te2.setText(builder);
}
}

Related

how can i underline a text word by word?

how can i underline word by word in a sentence in android studio? so my program would be like this if i click a button the underline will start at first and when i click again the button it will move again to the next word.
for Example:
_The_ *** *** ***** **** *** **** ***.
so if i want to click the button the underline will move next to it word or 3 asterisk.
The _***_ *** ***** **** *** **** ***.
and click again to the next asterisk.
this is my code using for this:
public class MainActivity extends AppCompatActivity {
Button btn;
TextView txt;
int counter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
btn = findViewById(R.id.button);
txt = findViewById(R.id.display);
txt.setText("the red fox jumps over the lazy dog.");
final String [] compare1 = txt.getText().toString().split("\\s");
final String arr[] = txt.getText().toString().split(" ",2);
final String fword = arr[0];
String rword = arr[1];
final String reprword = rword.replaceAll("[a-z]", "*");
txt.setText(fword + " " + reprword);
final String [] display = txt.getText().toString().split("\\s");
/*final ArrayList<String> getters = new ArrayList<String>(Arrays.asList(display));*/
btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if(counter <= display.length) {
if(compare1[counter].length() == display[counter].length())
{
txt.setText(formatText(fword + " " + reprword,display[counter]));
}
counter++;
}
else
{
}
}
});
}
public CharSequence formatText(String base, String highlight) {
int start = base.indexOf(highlight);
if (start >= 0) {
SpannableString span = new SpannableString(base);
span.setSpan(new UnderlineSpan(), start, start + highlight.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
return span;
}
return base;
}
}
I change the other half the sentence to test it for this.
base.indexOf(highlight) ==> indexOf() returns the first occurrence of highlight in base , thats why the underline span jumps to first "the" instead of the next occurrence. You can use indexOf(String str, int fromIndex).
The following code tracks the "fromIndex" in this variable "nextStartIndex", and also underlining resets to first word after completing the sentence.
public class UnderlineWordsActivity extends AppCompatActivity {
private Button btn;
private TextView txt;
private int counter=0;
private int nextStartIndex=0;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
btn = findViewById(R.id.button);
txt = findViewById(R.id.display);
txt.setText("the red fox jumps over the lazy dog.");
final String[] arr = txt.getText().toString().split(" ", 2);
final String firstWord = arr[0];
String remainingWords = arr[1];
final String reprword = remainingWords.replaceAll("[a-z]", "*");
String text = firstWord+" "+reprword;
txt.setText(text);
final String[] display = txt.getText().toString().split("\\s");
btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (counter >= display.length) {
counter = 0;
nextStartIndex = 0;
}
txt.setText(formatText(text, display[counter]));
counter++;
}
});
}
public CharSequence formatText(String base, String highlight) {
int start = base.indexOf(highlight,nextStartIndex);
nextStartIndex = start+highlight.length();
if (start >= 0) {
SpannableString span = new SpannableString(base);
span.setSpan(new UnderlineSpan(), start, nextStartIndex, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
return span;
}
return base;
}
}

How to display multiple EditText inputs after pressing Button in one TextView?

I'm in the beginning of my learning how to make apps. I want to make an app which should display randomized inputted tasks to do for the user. Firstly user should choose how many tasks would like to create and then write down tasks in EditText. I am able to create particular amount of EditText but I have no clue how to display all EditText input after pressing button. I have many versions of the code but non of them work. I got stuck and I need advice.
Here is one of my code version for the second activity.
public class TaskActivity extends AppCompatActivity {
LinearLayout containerLayout;
TextView receiverTV;
TextView tv;
TextView displayTaskTv;
EditText et;
Button btn;
Button randomTaskBtn;
int i = 0;
int size;
String inputEditText;
String inputTextView;
String stringsEt[];
String stringsTv [];
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_task);
containerLayout = (LinearLayout) findViewById(R.id.linear_layout);
receiverTV = (TextView) findViewById(R.id.receiver_textView);
Intent intent = getIntent();
int number = intent.getIntExtra("Number", defaultValue);
receiverTV.setText("You have chosen to add: " + number + " tasks!");
createEtTvBtn(number);
createBtn();
createTextView();
}
public void createEtTvBtn(int number) {
for (i = 1; i <= number; i++) {
tv = new TextView(this);
tv.setText("Task nr: " + i);
tv.setPadding(16, 16, 16, 16);
tv.setTextColor(Color.parseColor("#008b50"));
tv.setTextSize(20);
tv.setId(i + value);
containerLayout.addView(tv);
et = new EditText(this);
et.setHint("Enter task nr: " + i);
et.setId(i + value);
et.setLines(2);
containerLayout.addView(et);
btn = new Button(this);
btn.setText("Confirm task nr: " + i);
btn.setId(i + value);
containerLayout.addView(btn);
final List<EditText> allEditText = new ArrayList<EditText>();
final List<TextView>allTextView = new ArrayList<TextView>();
final List<Button>allButton = new ArrayList<Button>();
String[] stringsEditText = new String[(allEditText.size())];
String[] stringsTextView = new String[(allTextView.size())];
String[] stringsBtn = new String[(allButton.size())];
for(int i=0; i < allEditText.size(); i++){
stringsEditText[i] = allEditText.get(i).getText().toString();
}
for (int i=0; i < allTextView.size(); i++) {
stringsTextView[i] = allTextView.get(i).getText().toString();
size = allTextView.get(i).getText().toString().length();
}
for(int i=0; i < allButton.size(); i++){
stringsBtn[i] = allButton.get(i).getText().toString();
}
allTextView.add(tv);
allEditText.add(et);
allButton.add(btn);
allButton.get(0).setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
inputEditText = allEditText.get(0).getText().toString();
stringsEt = new String[] {allEditText.get(0).getText().toString()};
if (inputEditText.length() > 0) {
allTextView.get(0).setText(inputEditText);
allEditText.add(allEditText.get(0));
allEditText.get(0).setText("");
}
else if (inputEditText.length() ==0){
Toast.makeText(TaskActivity.this, "You need to write down your task", Toast.LENGTH_LONG).show();
}
inputTextView = allTextView.get(0).getText().toString();
stringsTv = new String[] {allTextView.get(0).getText().toString()};
if (inputTextView.length() > 0) {
allTextView.get(0).getText();
allTextView.add(allTextView.get(0));
}
}
});
}
}
private Button createBtn() {
randomTaskBtn = new Button(this);
randomTaskBtn.setText("Task");
containerLayout.addView(randomTaskBtn);
randomTaskBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
double luckyTask = Math.random();
luckyTask *=size;
int luckyIndex = (int)luckyTask;
displayTaskTv.setText(stringsTv[luckyIndex]);
}
});
return randomTaskBtn;
}
private TextView createTextView() {
displayTaskTv = new TextView(this);
displayTaskTv.setTextSize(20);
displayTaskTv.setTextColor(Color.parseColor("#dd2626"));
displayTaskTv.setText("");
containerLayout.addView(displayTaskTv);
return displayTaskTv;
}
}
Thank you for any constructive advices.
I am sure my code is big mess. I wanted to created more methods but I didn't succeed.
This is what you should do
Step 1 -
Create multiple EditTexts and store each one of them in an ArrayList say myEditTextList.
Step 2- Take data from all edit texts
String str = ""
for(EditText et: myEditTextList) {
str += et.getText().toString();
}
Step 3- Display data in str wherever you want.

Make selected text from Edittext Bold and not-bold

I'm trying to make a feature for my app where the user can make a selected text Bold but I also want to make it so that if the selected text is already bold, then the text shall be set to normal again, a kind of an undo-function.
I have tried over 100 of combinations without any succses!
CharacterStyle csBold = new StyleSpan(Typeface.BOLD);
CharacterStyle csNormal = new StyleSpan(Typeface.NORMAL);
int start = editText.getSelectionStart();
int end = editText.getSelectionEnd();
SpannableStringBuilder ssb = new SpannableStringBuilder(editText.getText());
ssb.setSpan(csBold, start, end, 1);
SpannableStringBuilder ssb2 = new SpannableStringBuilder(editText.getText());
ssb2.setSpan(csNormal, start, end, 1);
switch(item.getItemId()) {
case R.id.bold:
while(editText.isSelected()){
if(editText.getSelectionStart() + editText.getSelectionEnd() == ssb.getSpanStart(start) + ssb.getSpanEnd(end)){
editText.setText(ssb2);
return true;
}else{
editText.setText(ssb);
return true;
}
}
Update ANSWER
Edittext editext;
Button bold_btn , normal_btn , itlac;
CharacterStyle styleBold , styleItalc;
boolean bold = false;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
styleBold = new StyleSpan(Typeface.BOLD);
styleNormal = new StyleSpan(Typeface.NORMAL);
styleItalc = new StyleSpan(Typeface.ITALIC);
underLine = new UnderlineSpan();
editext = (Editext) findViewById(R.id.editext);
bold_btn = (Button) findViewById(R.id.button1);
italic_btn = (Button) findViewById(R.id.button2);
italic_btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String wholeText = username.getText().toString();
int start = username.getSelectionStart();
int end = username.getSelectionEnd();
SpannableStringBuilder sb = new SpannableStringBuilder(wholeText);
sb.setSpan(styleItalic, start, end, 0);
username.setText(sb);
}
});
........
.....
bold_btn.setOnClickListener(BoldbuttonListener);
normal_btn.setOnClickListener(normalbuttonListener);
}
View.OnClickListener BoldbuttonListener = new View.OnClickListener() {
#Override
public void onClick(View v) {
bold = !bold;
String wholeText = username.getText().toString();
int start = username.getSelectionStart();
int end = username.getSelectionEnd();
CharacterStyle passedStyle;
SpannableStringBuilder sb = new SpannableStringBuilder(wholeText);
if(bold) {
passedStyle = styleNormal;
}else {
passedStyle = styleBold;
}
sb.setSpan(passedStyle, start, end, 0);
editext.setText(sb);
}
};
the same for normal effect

Clear a TextView when EditText inputs

I have 2 EditText fields set up for numeric inputs, a button to start a calculation on the 2 inputs when pressed, and a TextView to display the result of the calculation. For repeated calculations I want to clear the TextView result as soon as either EditText is changed.
Following the reply to "A better way to OnClick for EditText fields" given by 'avalancha', my program clears the result when the first EditText field is changed, but retains the previous answer if only the second EditText field is changed. Yet I have used the same source code for both fields.
Can someone explain why, and how to cure this? my code is appended:
public class DoublesActivity extends ActionBarActivity {
private EditText textBox1, textBox2;
private Button calcButton;
private Context context;
#Override
protected void onCreate(Bundle outState) {
super.onCreate(outState);
setContentView(R.layout.activity_doubles); // Sets the layout .xml file
context = this.getApplicationContext();
textBox1 = (EditText) findViewById(R.id.editText1); //textBox1 holds a reference to the editText1 object in the xml layout
textBox2 = (EditText) findViewById(R.id.editText2);
textBox1.setText("");
textBox2.setText("");
final TextView textBox3 = (TextView) findViewById(R.id.textView1);
textBox2.setOnFocusChangeListener(new View.OnFocusChangeListener() {
#Override
public void onFocusChange(View v2, boolean hasFocus2) {
if (hasFocus2) {
textBox3.setText("");
}
}
});
textBox1.setOnFocusChangeListener(new View.OnFocusChangeListener() {
#Override
public void onFocusChange(View v1, boolean hasFocus1) {
if (hasFocus1) {
textBox3.setText("");
}
}
});
calcButton = (Button) findViewById(R.id.button1);
calcButton.setBackgroundColor(Color.CYAN);
calcButton.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
CharSequence userNumber1 = textBox1.getText(); //userNumber1 is a CharSequence holding the text in textBox1
CharSequence userNumber2 = textBox2.getText();
Float handicap1 = Float.parseFloat(userNumber1.toString()); //convert to integer
Float handicap2 = Float.parseFloat(userNumber2.toString()); //convert to integer
Float handicapT = calculate(handicap1, handicap2);
CharSequence userNumber = String.valueOf(handicapT);
if (handicapT > 98.5) {
userNumber = "Non-valid h'cap 1!";
}
if (handicapT < -98.5) {
userNumber = "Non-valid h'cap 2!";
}
textBox3.setText(userNumber); // put result in the TextView
}
});
}
#Override
protected void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
TextView textBox3 = (TextView) findViewById(R.id.textView1);
CharSequence userNumber = textBox3.getText();
outState.putCharSequence("savedText", userNumber);
}
#Override
protected void onRestoreInstanceState(Bundle savedInstanceState) {
super.onRestoreInstanceState(savedInstanceState);
final TextView textBox3 = (TextView) findViewById(R.id.textView1);
CharSequence userText = savedInstanceState.getCharSequence("savedText");
textBox3.setText(userText);
}
Float calculate(Float h1, Float h2) {
float[] handicapArray;
handicapArray = new float[29];
handicapArray[0] = 28;
handicapArray[1] = 26;
handicapArray[2] = 24;
handicapArray[3] = 22;
handicapArray[4] = 20;
handicapArray[5] = 18;
handicapArray[6] = 16;
handicapArray[7] = 14;
handicapArray[8] = 12;
handicapArray[9] = 11;
handicapArray[10] = 10;
handicapArray[11] = 9;
handicapArray[12] = 8;
handicapArray[13] = 7;
handicapArray[14] = 6;
handicapArray[15] = 5;
handicapArray[16] = 4.5F;
handicapArray[17] = 4;
handicapArray[18] = 3.5F;
handicapArray[19] = 3;
handicapArray[20] = 2.5F;
handicapArray[21] = 2;
handicapArray[22] = 1.5F;
handicapArray[23] = 1;
handicapArray[24] = 0.5F;
handicapArray[25] = 0;
handicapArray[26] = -0.5F;
handicapArray[27] = -1;
handicapArray[28] = -1.5F;
int index1 = -1;
for (int i = 0; i < 29; i++) {
if (Math.abs(h1 - handicapArray[i]) < 0.001) {
index1 = i;
break;
}
}
if (index1 == -1) {
EditText textBox1 = (EditText) findViewById(R.id.editText1);
textBox1.setText("");
}
int index2 = -1;
for (int i = 0; i < 29; i++) {
if (Math.abs(h2 - handicapArray[i]) < 0.001) {
index2 = i;
break;
}
}
if (index2 == -1) {
EditText textBox2 = (EditText) findViewById(R.id.editText2);
textBox2.setText("");
}
int indexT = (index1 + index2) / 2; // Correctly rounds indexT halves down.
Float result = handicapArray[indexT];
if (index1 == -1) {
result = 99F;
}
;
if (index2 == -1) {
result = -99F;
}
;
return result;
}
Use addTextChangedListener to clear textview.
editText.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 start,
int before, int count) {
resultTextView.setText("");
}
});
For example please use below link
android on Text Change Listener

how to do highlight on Strings

I only want to find the words on the Diccionario Array and highlight but show other words to
Example: If I search "spannable", i want to return the same text but with the words who find it on highlight or other color !
public class FindString extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.search_string);
final Button btnSearch = (Button) findViewById(R.id.searchBtn);
final EditText Searchtxt = (EditText)findViewById(R.id.textSearch);
final String[] Diccionario = {"hola","adios","ayer","hoy","maƱana"};
btnSearch.setOnClickListener(new View.OnClickListener() {
public void onClick(View v){
String FinalText = " " ;
String SearchText ="";
SearchText = Searchtxt.getText().toString();
String[] split = SearchText.split(" ");
for(int i=0; i<split.length; i++)
{
for(int j=0; j<Diccionario.length;j++)
{
if(split[i].equals(Diccionario[j]))
{
FinalText = FinalText +" "+split[i];
}
}
}
}
emphasized text
try this
{
final SpannableStringBuilder sb = new SpannableStringBuilder(FinalText);
final ForegroundColorSpan fcs = new ForegroundColorSpan(Color.rgb(158, 158, 158));
// Span to set text color to some RGB value
final StyleSpan bss = new StyleSpan(android.graphics.Typeface.BOLD);
// Span to make text bold
sb.setSpan(fcs, 0, 4, Spannable.SPAN_INCLUSIVE_INCLUSIVE);
// Set the text color for first 4 characters
sb.setSpan(bss, 0, 4, Spannable.SPAN_INCLUSIVE_INCLUSIVE);
// make them also bold
yourTextView.setText(sb);
}

Categories

Resources