How to display HTML string resource with parameters in TextView? - java

I have a HTML string like this:
Some text %1$s
<br></br>
StackOvewflow
<br></br>
Contact: example#gmail.com
How to display it so it shows the line breaks and links to the text properly in a TextView?
I have tried both
Spanned text = null;
if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.N) {
text = Html.fromHtml(getString(R.string.text, "parameter"), Html.FROM_HTML_MODE_LEGACY);
}
else
{
text = Html.fromHtml(getString(R.string.text, "parameter"));
}
textView.setText(text);
and
String text = TextUtils.htmlEncode(getString(R.string.text, "parameter"));
textView.setText(text);
In the XML textView is defined as
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/text"
android:text="#string/text"
/>
When displayed, it just looks like
Some text parameter StackOvewflow Contact: example#gmail.com
without any line breaks or links

I used the same code you shared
Spanned text = null;
if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.N) {
text = Html.fromHtml(getString(R.string.text, "parameter"),
Html.FROM_HTML_MODE_LEGACY);
}
else
{
text = Html.fromHtml(getString(R.string.text), "parameter");
}
textView.setText(text);
seems to be working fine for me.
seems to be working

Related

How to format android EditText after paste?

I am new to Java, I need to know how do I format android EditText after pasting a number to it?
I have following XML in my XML file to EditText:
<EditText
android:id="#+id/user_number_id"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_gravity="center_vertical"
android:layout_marginStart="#dimen/_12sdp"
android:layout_marginBottom="#dimen/_12sdp"
android:background="#color/white"
android:inputType="number"
android:maxLength="14"
android:paddingTop="#dimen/_2sdp"
android:text="Your Number: "
android:textSize="#dimen/_15sp" />
For instance, after I paste "23989723412" to EditText, it should format it automatically to "129.897.234-12".
I did some research, however, I am not sure what event triggers when a number is pasted in EditText, but it may have to do something with afterTextChanged but I don't know how to do it for this purpose in Java?
Thank you in advance.
If you want to get a dot every 3 numbers for improved reading.
e.x. 1290030022 = 1.290.030.022
Feel free to use the code snippet below in your Activity.java:
EditText editText = findViewById(R.id.myeditText);
try {
DecimalFormat decimalFormat = new DecimalFormat();
Integer value = Integer.parseInt(editText.getText().toString());
String format = decimalFormat.format(value);
System.out.println("Result:" + format);
}catch (Exception e){
e.printStackTrace();
}

How to customize setError message in Android Studio with Java

I have several error messages in an Android Studio app using Java and I cannot figure out how to customize their appearance. I have consulted several answers on this site but none of them have worked for what I want.
This is what the error message looks like.
I want to change the colors of the black background, the white text, and the red line and icon.
This is the code for the error message,
String email = editTextEmail.getText().toString().trim();
String password = editTextPassword.getText().toString().trim();
if(email.isEmpty()){
editTextEmail.setError("Please enter an email.");
editTextEmail.requestFocus();
return;
}
and this is the code for the editText object.
<EditText
android:id="#+id/login_email"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_margin="8dp"
android:gravity="center"
android:hint="Email"
android:padding="8dp"
android:drawableLeft="#drawable/email_icon"
android:textColor="#417577"
android:textSize="25dp" />
How do I change the colors displayed in the error message? Also, is there a way to set these color changes for the whole app and not just individually?
Thank you!
After googling little bit I found some answers for you. Here I am implementing those sites.
devdeeds git repo
findnerd
xspdf
I am implementing that source code which looks like good for me
It is easy way to change color. If you have idea of html than you might see here you are just changing color by html format.
editText.setError(Html.fromHtml("<font color="#000000">"error!"</font>"));
Following source code used in java
int errorColor;
final int version = Build.VERSION.SDK_INT;
if (version >= 23) {
errorColor = ContextCompat.getColor(getApplicationContext(), R.color.errorColor);
} else {
errorColor = getResources().getColor(R.color.errorColor);
}
String errorString = "This field cannot be empty"; // your error message
ForegroundColorSpan foregroundColorSpan = new ForegroundColorSpan(errorColor);
SpannableStringBuilder spannableStringBuilder = new SpannableStringBuilder(errorString);
spannableStringBuilder.setSpan(foregroundColorSpan, 0, errorString.length(), 0);
editTextView.setError(spannableStringBuilder);

How to set dynamically color for TextView in Android

In my application I want show some text into TextView, and I get this text from server.
I should use just one textView in XML layout, and I should set color for this Texts.
My XML :
<TextView
android:id="#+id/rowExplore_userName"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="#dimen/size3"
android:layout_marginTop="#dimen/padding8"
android:layout_toRightOf="#+id/rowExplore_imageCard"
android:fontFamily="sans-serif"
android:gravity="left|center_vertical"
android:text="Adam"
android:textColor="#color/colorPrimary"
android:textSize="#dimen/font14" />
JSON :
"name": "Adam Sandel",
"info": "liked",
"movieName": "SpiderMan",
Java code :
rowExplore_userName.setText(response.getName() + response.getInfo() + response.getMovieName() );
I want set color dynamically such as below image :
How can I it? Please help me
You can use HTML
String text = "<font color=#cc0029>First Color</font> <font color=#ffcc00>Second Color</font>";
yourtextview.setText(Html.fromHtml(text));
A better approach to this is to create a string resource with appropriate HTML tags:
<string name="html_string" formatted="false">
<![CDATA[
<font color="yellow">%s</font> %s <font color="yellow">%s</font>
]]>
</string>
And then get that string with resources:
String htmlString = getString(R.strings.html_string, response.getName(), response.getInfo(), response.getMovieName());
rowExplore_userName.setText(htmlString);
You can use SpannableString if you want to avoid using HTML tags
TextView textview = (TextView)findViewById(R.id.textview);
Spannable wordToSpan = new SpannableString("Your text is here");
wordToSpan.setSpan(new ForegroundColorSpan(Color.BLUE), indexStart, indexEnd, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
textView.setText(wordToSpan);
and it is more flexible since you can make more changes to your text (text size, bold/italic, etc)
I used this code:
String colorStr="#FFFFFF" //put your hex color
int color = Color.parseColor(colorStr);
editText.setTextColor(color);
I would have another approach just create one method
public String getColoredString(String pname) {
Random rnd = new Random();
int color = Color.argb(255, rnd.nextInt(256), rnd.nextInt(256), rnd.nextInt(256));
Spannable wordToSpan = new SpannableString(pname);
wordToSpan.setSpan(new ForegroundColorSpan(color), 0, pname.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
return wordToSpan.toString();
}
and use above method
rowExplore_userName.setText(getColoredString(response.getName())+getColoredString(response.getInfo())+getColoredString(response.getMovieName()));
this should work.

Android TextView new line isn't working

I found the Answer I will accept it in 2 days time
I have been trying to create an activity that can display multiple messages for the user, in order to fit everything in the text view I need to create three lines. My search online hasn't given me any solutions, here is what I have tried
Java
"\n"
"\r\n"
newLineChar = System.getProperty("line.separator")
messageTextView.setText(Html.fromHtml("This\n Is\n A Test"));
messageTextView.setText(Html.fromHtml("This<br> Is<br> A Test"));
xml
android:lines="3"
android:maxLines="3"
Misc.
Hardcoding the string value directly into setText()
Various combinations of all of the above
removing android:clickable="false"
removing android:cursorVisible="false"
removing android:focusable="false"
removing android:focusableInTouchMode="false"
Code snippet:
// Message passed to next activity via putExtra()
message = "This\n Is\n A Test";
// Next Activity
TextView messageTextView = (TextView) findViewById(R.id.messageToUser);
String message = getIntent().getStringExtra("message");
messageTextView.setText(message);
Current and Updated XML for the TextView:
<TextView
android:id="#+id/messageToUser"
android:layout_width="0dp"
android:layout_height="200dp"
android:background="#90FFFFFF"
android:ems="10"
android:fontFamily="serif"
android:text=""
android:textAlignment="center"
android:textColor="#android:color/black"
android:textSize="30sp"
android:textStyle="bold"
tools:layout_constraintTop_creator="1"
tools:layout_constraintRight_creator="1"
android:layout_marginStart="165dp"
android:layout_marginEnd="165dp"
app:layout_constraintRight_toRightOf="parent"
android:layout_marginTop="209dp"
tools:layout_constraintLeft_creator="1"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintTop_toTopOf="parent" />
If this helps, I'm on Windows 7, Android Studio 2.3.2, Java 1.8, designing an App Specifically for SM-T580 (Samsung Tab A 10.1"), the TextView's parent is the base ConstraintLayout of the component tree
try this \n corresponds to ASCII char 0xA, which is 'LF' or line feed
tv.setText("First line " + System.getProperty("line.separator") + "Line 2"+ System.getProperty("line.separator") + "Line 3");
String String1 = "value 1";
String String2 = "value 2";
TextView.setText(String1 + "\n" + String2);
or try this
string = string.replace("\\\n", System.getProperty("line.separator"));
for hardcore string try this
<string name="value"> This\nis a sample string data</string>
or
<string name="value> This<br>is a sample<br> String data</string>
There is no need to set for the android:inputType because this is a TextView. These are the steps that I did to successfully implement the new line:
Make sure that android:maxLine is not set to 1. If you set this to 1, it will not implement new line. [Refer to the screenshot]
set maxLine inside xml file
If you want to manipulate a string that is not constant or not declared inside your string.xml, put System.getProperty("line.separator") between two string. In my case I put
phoneNumber = memberProfile.getPhoneNumber() + System.getProperty("line.separator") + "09162343636";
If you have a constant string or you have set it to your string.xml file, just put "\n" and that works perfectly. Refer sample below:
string.xml
I was using a recyclerView to display so here is the output of this:
Output
\r\n works for me
messageTextView.setText("First line\r\nNext line");
Or alterantively you can also use string variable
<string name="sample_string"><![CDATA[some test line 1 <br />some test line 2]]></string>
so wrap in CDATA is necessary and breaks added inside as html tags
This works for me:
messageTextView.setText(Html.fromHtml("This<br/>Is<br/>A Test"));
Explanation: The TextView content is HTML content. <br/> is an HTML tag for a line break.
messageTextView.setText(Html.fromHtml("This\n Is\n A Test"));
try this. It work for me
message = "This"+System.getProperty("line.separator")
+ "Is" + System.getProperty("line.separator") + "A Test";
// Next Activity
TextView messageTextView = (TextView) findViewById(R.id.messageToUser);
String message = getIntent().getStringExtra("message");
messageTextView.setText(message);
Add this code to res/strings
<string name="myhtml">
<![CDATA[
<p>This is a <b>bold</b> and <i>italic</i> text</p>
<p>This is another paragraph of the same string.</p>
]]>
</string>
Add this your Activity class
TextView tv = (TextView)findViewById(R.id.foo);
tv.setText(Html.fromHtml(getString(R.string.myhtml)));
Found the issue I had to take android:inputType="textPersonName" out of the XML for the TextView. I had mistakenly left the Html.fromHtml(...) method call when I initially removed android:inputType="textPersonName". After calling message.setText("This\n Is\n A Test"); with NO android:inputType="textPersonName".Everything worked as expected.
For final clarity....
The newline character "\n" will not work if the input type is "textPersonName"
The newline character for Andriod is "\n"
Tried many finally this worked for me
messageTextView.setText(string.replace("\n", ""+System.getProperty("line.separator")));

change the font color from activity

I have a java code for an apk. I want to change the color from java activity
try {
String s = "";
JSONArray jArray = new JSONArray(result);
for(int i=0; i<jArray.length();i++){
JSONObject json = jArray.getJSONObject(i);
s = s +
"User : "+json.getString("username")+"\n"+
"Send : "+json.getString("time")+
" & "+json.getString("date")+"\n"+
Now, I want to set 2 different color, for the "user" one color and json.getString("username") a different color as well as font weight, bold or not.
and my XML code is
<TextView
android:id="#+id/result"
android:background="#2E2EFE"
android:layout_width="match_parent"
android:textColor="#F3F781"
android:textSize="24dp"
android:layout_height="wrap_content"
android:paddingLeft="20sp"
android:text="TextView"/>
But I do not want to change the color from XML

Categories