Add another Word in TextView Android - android

I have one sentence with 3 TextView in my RecyclerView. The picture is like below :
In that picture, I have one sentence in 3 TextView, there are "1" "HOT, MORE CHILLI" and "Pizza". This is my RecyclerView Binding code :
try {
view.txtArticlesName.setText(/*orderList.getJSONObject(position).getString("quantityValue") +*/
/*orderList.getJSONObject(position).getString("spesial-request").replaceAll("[\\\"\\[\\]]", "") + */
orderList.getJSONObject(position).getString("bezeich"));
view.txtQty.setText(orderList.getJSONObject(position).getString("quantityValue"));
view.txtReqList.setText(orderList.getJSONObject(position).getString("spesial-request").replaceAll("[\\\"\\[\\]]", ""));
} catch (JSONException e) {
e.printStackTrace();
}
I want to Join all of TextView with only one 'TextView` dynamicly. I'll try this :
view.txtArticlesName.setText(/*orderList.getJSONObject(position).getString("quantityValue") +*/
/*orderList.getJSONObject(position).getString("spesial-request").replaceAll("[\\\"\\[\\]]", "") + */
orderList.getJSONObject(position).getString("bezeich"));
But its not work, its not bind the data, so the TextView just show the default text "Hello World". Can TextView do this? I read about Spannable too but i dont know how its work to add new word in one TextView. Or there is another way to do this? Any suggest and answer will helpfull for me. Thanks before.

Simply concat the Strings in your TextView.
String string1 = "Hello", string2 = "HOT CHILLI", string3 = "PIZZA";
TextView textView = (TextView) findViewById(R.id.your_textView);
textView.setText(string1.concat(string2).concat(string3));
Or you could also append it to the existing TextView's text.
textView.setText(textView.getText().toString.concat(string2));
EDIT:
Collect the data from the server in String variables, and then pass those variables to the TextView.
String string1, string2, string3;
try {
string1 = orderList.getJSONObject(position).getString("quantityValue");
string2 = orderList.getJSONObject(position).getString("spesial-request").replaceAll("[\\\"\\[\\]]", "");
string3 = orderList.getJSONObject(position).getString("bezeich"));
String final = string1.concat(string2).concat(string3);
view.txtView.setText(final);
} catch (JSONException e) {
e.printStackTrace();
}

Use '+' operator or StringBuilder to join 2 or more strings and set the resultant string into a single textview.
If you want to have some part of text with different font, color, size, bold etc, you can use Spannable string or Html.fromHtml()

you can make and use spannable String like below :
private void addSpannableString(){
//"1" "HOT, MORE CHILLI" and "Pizza"
String one= "1";
String two= "HOT, MORE CHILLI";
String three= "Pizza";
String mergeString= one + two + three;
Spannable spannable = new SpannableString( mergeString );
StyleSpan boldSpan = new StyleSpan( Typeface.BOLD );
spannable.setSpan( boldSpan, mergeString.indexOf(two), mergeString.indexOf(three), Spannable.SPAN_INCLUSIVE_INCLUSIVE );
textview.setText(mergeString);
}
There are many methods are available to make Spans including colors and Typefaces

Use TextView.append(CharSequence text) to add more text to it.
Append the specified text to the TextView's display buffer, upgrading
it to BufferType.EDITABLE if it was not already editable

The Difference between GetString And OptString is:
From Documentation
OptString returns the empty string ("") if the key you specify doesn't
exist. GetString on the other hand throws a JSONException.
Use getString if it's an error for the data to be missing, or optString if you're not sure if it will be there.

I solved this with a little disappointed . Here my final code :
try {
view.txtArticlesName.setText(orderList.getJSONObject(position).getString("quantityValue") + " " +
orderList.getJSONObject(position).optString("spesial-request").replaceAll("[\\\"\\[\\]]", "") + " " +
orderList.getJSONObject(position).getString("bezeich"));
} catch (JSONException e) {
e.printStackTrace();
}
with getString :
with optString :
I change getString with optString and operator + work now. I'm not fully undertand why getString not work but optString work.
Thank you very much for all anwser, +1 from me

Related

Remove all <tag></tag> with text between

I'm trying to remove all text tagged like this (including the tags)
<tag>TEXT</tag>
from a String.
I have tried
.replaceAll("<tag>.+/(tag)*>", "")
or
.replaceAll("<tag>.*(tag)*>", "")
but neither works correctly and I can't replace the tagged text with ""
I don't know exactly what you want, so here are a few options:
String text = "ab<tag>xyz</tag>cd";
// Between
text.replaceAll("<tag>.+?<\/tag>", "<tag></tag>"); // ab<tag></tag>cd
// Everything
text.replaceAll("<tag>.+?<\/tag>", ""); // abcd
// Only tags
text.replaceAll("<\/?tag>", ""); // abxyzcd
EDIT:
The problem was the missing ? after the .+. The question mark only matches the first occurence, so it works when multiple tags are present which was the case.
Change to this ,
String nn1="<tag>TEXT</tag>";
nn1=nn1.replace("<tag>","");
nn1=nn1.replace("</tag>","");
OR
String nn1="<tag>TEXT</tag>";
nn1=nn1.replaceAll("<tag>","");
nn1=nn1.replaceAll("</tag>","");
Output : TEXT
I hope this helps you.
public static void removeTAG()
{
String str = "<tag>Your Long String</tag>";
for(int i=0;i<str.length();i++)
{
str = str.replace("<tag>", "");
str = str.replace("</tag>", "");
}
System.out.println(str);
}
Here what i did and output was as expected
Output Your Long String
You can use the below regular expression.
.replaceAll("<tag>.+?<\/tag>", "<tag></tag>");
This removes all the tags whether it's an HTML or an XML tag.

InputType doesn't work when text is set with setText

I have set android:inputType="text|textCapWords" to my EditText. When I type something in the field, the first letter is correctly capitalised, but if I set a full capitalised (or full lowercase) text using the setText() method, the text remains fully capitalised (or in lowercase).
How can I use setText for the text to comply with the input type?
As #Amarok suggests
This is expected behavior. You have to format the text yourself before
using the setText() method
But if you want to format your text just like android:inputType="text|textCapWords you can use the following method:
public static String modifiedLowerCase(String str){
String[] strArray = str.split(" ");
StringBuilder builder = new StringBuilder();
for (String s : strArray) {
String cap = s.substring(0, 1).toUpperCase() + s.substring(1).toLowerCase();
builder.append(cap + " ");
}
return builder.toString();
}
and use it like
textView.setText(modifiedLowerCase("hEllo worLd"));
It will convert it like :
Hello World
You can check for your editText Type constants, and add simple .toUpperCase() to the text you're adding, like this:
if(mEditText.getInputType() == TYPE_TEXT_FLAG_CAP_CHARACTERS+ TYPE_CLASS_TEXT)
mEditText.setText("Some text".toUpperCase());
else
mEditText.setText("some text");
More for input types constants can be found here
Use this
EditText.getText().clear();
EditText.getText().append("test");
rather than
EditText.setText("test");
so that the text that has been set follows the input type behavior

Is it possible inserting Image into TextView using string argument approach?

As we see in https://stackoverflow.com/a/10144094/3286489, we could add arguments into our String parameter through the %1$d etc. But I don't know how to add image there.
We could add image to our String as we see in https://stackoverflow.com/a/3177667/3286489 using spannable. But the position of the image within the text need to explicitly stated.
So my question is, is there a way where we could insert our image into the TextView (I'm okay using spannable), using parameterized approach as https://stackoverflow.com/a/10144094/3286489?
Here's what I've done before:
eg. your string could be: "This is an [img]".
Find the position of "[img]" and replace it with ImageSpan
EDIT: Regex pattern could be something like
String message = "This is an [img]";
Pattern MY_PATTERN = Pattern.compile("\\[img\\]");
Matcher matcher = MY_PATTERN.matcher(message);
// Check all occurrences
while (matcher.find()) {
System.out.print("Start index: " + matcher.start());
System.out.print(" End index: " + matcher.end());
}
string.xml
<string name="var">Image %1$s and %2$s</string>
MainActivity.java
TextView textView = (TextView) findViewById(R.id.text);
String v1 = "%1$s";
String v2 = "%2$s";
String test = getString(R.string.var, v1, v2);
Spannable span = Spannable.Factory.getInstance().newSpannable(test);
span.setSpan(new ImageSpan(getBaseContext(), android.R.drawable.star_on),
test.indexOf(v1), test.indexOf(v1) + v1.length(),
Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
span.setSpan(new ImageSpan(getBaseContext(), android.R.drawable.star_on),
test.indexOf(v2), test.indexOf(v2) + v2.length(),
Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
textView.setText(span);

set textview's text using Html.fromHtml inside a loop?

Is possible to use Html.fromHtml to the String fetchData, to change some of the text style? This text assigned to a textView outside the loop.
Here is the related code:
if( c != null && c.moveToFirst() ){
while (c.isAfterLast()==false) {
String gtWord = c.getString(1);
String gtDef = c.getString(2);
fetchData = fetchData + getResources().getString(R.string.wordLabel) + gtWord + "\n"
+ getResources().getString(R.string.transLabel) + gtDef + "\n\n";
c.moveToNext();
}
getData.setText(fetchData)
Right now I'm using strings.xml in which I've set the text like this:
<b>Word: </b>
but the style is ignored. I'found some related questions and I've tried to do it without using strings.xml also, but the only tag recognized is the , all others ignored. I'm supposing that the problem is that I'm using mixed variables and hardcoded text inside loop, because I tested it outside the loop like this:
getData.setText(Html.fromHtml("<b>This<b/> is <u>underlined<u/> text")
and it's working.
Declaire your string like this
<string name="wordLabel"><![CDATA[<b>Word: </b>]]></string>
From documentaion you can also write it as
<string name="word_label"><b>Word: </b></string> // here I have chnaged your string name wordLabel to word_label. you should follow naming convension.
Notice that the opening bracket is HTML-escaped, using the < notation.

linkyfy some text in TextView

I have a String in TextView and I want to Linkify a substring from that string. for example:
click here to know more.
I'm getting the string dynamically. So i have to search if it has click here and convert that to link .How can I linkify "click here".
To find a pattern inside a text and replace it, use this:
Pattern p = Pattern.compile("click here");
Matcher m = p.matcher("for more info, click here");
StringBuffer sb = new StringBuffer();
boolean result = m.find();
while(result) {
m.appendReplacement(sb, "click here");
result = m.find();
}
m.appendTail(sb);
String strWithLink = sb.toString();
yourTextView.setText(Html.fromHtml(strWithLink));
yourTextView.setMovementMethod(LinkMovementMethod.getInstance())
This code will search inside your string and replaces all "click here" with a link.
And at the end, do NOT add android:autoLink="web" to you XML resource (section TextView), otherwise A-tags are not rendered correctly and are not clickable any longer.
did your tried like this
Click here
for setting it to textview
 
//get this thru supstring
String whatever="anything dynamically";       
String desc = "what you want to do is<a href='http://www.mysite.com/'>"+whatever+":</a>";
yourtext_view.setText(Html.fromHtml(desc));
String urlink = "http://www.google.com";
String link = "<a href=\"+urlink+ >link</a>";
textView.setText(Html.fromHtml(link));
Raghav has the right approach using the fromHtml() method, but if you're searching for for a String with a fixed length, you could do something like:
String toFind = "click here";
if(myString.indexOf(toFind) > -1){
String changed = myString.substring(0, myString.indexOf(toFind)) + "<a href='http://url.whatever'>" + myString.substring(myString.indexOf(toFind), myString.indexOf(toFind) + toFind.length()) + "</a>" + myString.substring(myString.indexOf(toFind) + toFind.length());
}
else {
//String doesn't contain it
}
When setting the actual text, you need to use: tv.setText(Html.fromHtml(yourText)); or else it will just appear as a String without any additives. The fromHtml() method allows you to use certain HTML tags inside your application. In this case, the tag which is used for linking.

Categories

Resources