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")));
Related
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();
}
I am making a calculator app in Android Studio(Mac OS) in which I'm trying to include square(x^2) Button.
I've set my square as a TextView.
I've tried all the links mentioned but none worked for me to type it as in proper equation format.
<TextView
android:id="#+id/square"
style="?android:attr/borderlessButtonStyle"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="top"
android:layout_marginBottom="-3dp"
android:layout_marginLeft="-20dp"
android:layout_marginStart="-5dp"
android:padding="15dp"
android:textColor="#color/black"
android:textSize="18sp" />
I've also tried below code in MainActivity.java file:-
squareButton = findViewById(R.id.square);
squareButton.setText(Html.fromHtml("x<sup>2</sup>"));
Examples tried
Source 1 Source 2 Didn't work!
P.S. I've set minSdkVersion 14 and targetSdkVersion 26!
Android has native support for sub/superscript type text know as SubscriptSpan and SuperscriptSpan
Sample Usage of Superscript (eg X^2)
String text = "X2";
SuperscriptSpan superscriptSpan = new SuperscriptSpan();
SpannableStringBuilder builder = new SpannableStringBuilder(text);
builder.setSpan(
superscriptSpan,
text.indexOf("2"),
text.indexOf("2") + String.valueOf("2").length(),
Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
yourTextView.setText(builder);
I have found a really good example.
Just do some short research, Html.fromHtml is deprecated in Android N+.
Correct way should be this:
strButton = Html.fromHtml(html,Html.FROM_HTML_MODE_LEGACY);
Just do a check like #Vishva Dave 's comment, for android versions:
String strButton;
String html = "x<sup>2</sup>";
if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.N) {
strButton = Html.fromHtml(html,Html.FROM_HTML_MODE_LEGACY);
}
else{
strButton = Html.fromHtml(html);
}
squareButton.setText(strButton);
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.
I've tried for two day now to append an image to a TextView, but it didn't work. I have tried this for Android 6/API Level 23. ImageSpan, Html.fromHtml and other Methods did not work. So is it possible to append image (Bitmap) between other words in a TextView on Android 6?
EDIT
Here is the XML:
<TextView
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceMedium"
android:layout_width="match_parent"
android:text="------"
android:gravity="bottom|left"
android:typeface="monospace"
android:id="#+id/mainTextView1"
android:textIsSelectable="true"/>
And image span Code:
SpannableStringBuilder ssb = new SpannableStringBuilder(mOutEditText.getText()); ssb.setSpan(new ImageSpan(bitmapArray.get(0), ImageSpan.ALIGN_BASELINE), cursorPosition, cursorPosition+2, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE); mOutEditText.setText(ssb, BufferType.SPANNABLE);
Add image in xml
<TextView
android:drawableBottom="#drawable/ic_add_circle_black_24dp"
android:drawableEnd="#drawable/ic_add_circle_black_24dp"
android:drawableLeft="#drawable/ic_add_circle_black_24dp"
android:drawablePadding="#drawable/ic_add_circle_black_24dp"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
programmatically
textView1.setCompoundDrawables(left,top,right,bottom);
Or only left
textView1.setCompoundDrawables(left,null,null,null);
I have found the solution now for Api 21, 22, 23+:
private void appendImage(Bitmap bmp)
{
tv.setTransformationMethod(null);
SpannableString ss = new SpannableString(" ");
ss.setSpan(new ImageSpan(bmp, ImageSpan.ALIGN_BASELINE), 0, 1, Spanned.SPAN_INCLUSIVE_EXCLUSIVE);
tv.append(ss);
}
And in the XML:
android:textAllCaps="false"
The error was that in api level 21+ you have to set the TransformationMethod null.
If you want to set the background of the TextView use the following methods:
txt.setBackgroundResource(int rsid);
txt.setBakgroundDrawable(Drawable object);
If by append, you mean you want to add it to the end of the TextView, then use an ImageView for the image. Or you can overlay your TextView in an ImageView
It is not possible to add images between text in a TextView. You can add an image a TextView at the start and end. This is done with
android:drawableLeft
How to insert a text in EditText at the cursor position? editText.setText erases the current text and sets the new one, which is not what I want. editText.setText(editText.getText() + "my text"); inserts the text at the end, that's also not the case.
Its very easy to do this :
int start =editText.getSelectionStart(); //Get cursor position with this function
String str = "my text";//String you want to insert
editText.getText().insert(start, str); //This will get the text and insert the String str at the current position.
Hope this Helps!
are you perhaps talking about settings the hint text ?
editText.setHint("Enter Text Here");
in XML
android:hint="Enter Text Here"
If this is not what you are looking for then please alaborate the problem a bit more
Add \n before the text you want to add...
var.setText(var.getText() + "\nnewtext");