Running on my Samsung Galaxy Note, the below code logs 28.0 for each log statement. Am I doing something wrong?
label = new TextView(context);
Log.e("text size", "" + label.getTextSize());
label.setTextAppearance(context, android.R.attr.textAppearanceLarge);
Log.e("text size", "" + label.getTextSize());
label.setTextAppearance(context, android.R.attr.textAppearanceSmall);
Log.e("text size", "" + label.getTextSize());
Use the style class, not attr.
label.setTextAppearance(context, android.R.style.TextAppearance_Large);
This same point of confusion was reported here: TextView.setTextAppearance not working.
Related
I'm using below code on android nougat and it's working:-
Html.fromHtml("<strike> " + myText + "</strike"));
But on Marshemellow it's not working, i mean the <strike> tag.
Is there any way to get working on all devices ?
myText is a dynamic text received in recyleView:
public void onBindViewHolder(final DealsAdapter.MyViewHolder holder, final int position) {
final DataDeals feedItem = feedItemList.get(position);
Usage :-
holder.oldPrice.setText(fromHtml("<strike>" + feedItem.getOldPrice() + "</strike>"));
this method is deprecated.
I should use this code:
#SuppressWarnings("deprecation")
public static Spanned fromHtml(String html){
Spanned result;
if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.N) {
result = Html.fromHtml(html,Html.FROM_HTML_MODE_LEGACY);
} else {
result = Html.fromHtml(html);
}
return result;
}
usage:
fromHtml("<strike> " + myText + "</strike"));
EDIT
Do not forget to close your triangular bracket:
fromHtml("<strike> " + myText + "</strike>"));
instead of your: fromHtml("<strike> " + myText + "</strike"));
I was having the same problem where StrikethroughSpan was not working (for some devices) on a TextView inside a RecyclerView item layout. It worked fine on my Pixel OS 8.1, but didn't work on a Nexus 6 OS 7.1.1.
In my case I realised that some constraints in my layout were causing the issue. I changed the way I had implemented the layout a little bit and the StrikethroughSpan started working again. Pay attention to TextViews with wrap_content widths and heights and positioned in a Relative layout. Things that might affect the size of the TextView might be causing this issue. Unfortunately I didn't get to the root cause of the problem, but I hope this might help other people with similar problems.
As a note, both solutions to strike through the text work for me:
Html.fromHtml("<strike> " + myText + "</strike"));
or
SpannableStringBuilder spanText = new SpannableStringBuilder("my_awesome_text");
spanText.setSpan(new StrikethroughSpan(), 0, textToBeDisplayed.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
myTextView.setText(spanText);
In addition to what Vyacheslav has mentioned, please check that no Font Family is set on your TextView. I spent nearly 4 hours debugging this issue and removing the FontFamily from the TextView solved my issue.
I have this code for setting the text of a TextView:
TextView txt = new TextView(this);
txt.setText(Html.fromHtml("<b>" + m.getTitle() + "</b>" + "<br />" + "<small>" + m.getText() + "</small>" + "<br />");
The <small> mark is working, but I'd like to set the text size according to my dimensions defined in the dimens.xml file, which I use for all other text in my application. Adding the TextView through an xml layout is not an option since I don't know how many TextViews I'll be adding.
Dimensions in the dimens.xml file are set up like <dimen name="text_size_320dp_small">16sp</dimen>.
How can I apply these dimensions to my text formatted with Html.fromHtml?
Thanks a lot.
I have tested following code myself. You can do it like this.
txt.setText(Html.fromHtml("<b>" + m.getTitle() + "</b>" + "<br />"
+ "<font textsize="
+ getResources().getDimension(R.dimen.text_size_320dp_small) + ">" + m.getText()
+ "</font>" + "<br />"));
[Updated]:
Just came up with some references and updates :
You can store this in strings.xml
<string name="mystring"><font size = "%s"></string>
In code you can write as:
int sptopx = getResources().getDimensionPixelSize(R.dimen.text_size_320dp_small);
Spanned modified = Html.fromHtml( context.getString(R.string.mystring, sptopx) );
myTextView.setText(spanned);
TextView txt = new TextView(this);
txt.setText(
Html.fromHtml(
"<b>" + m.getTitle() + "</b>" +
"<br />" +
modified +
">" + m.getText() + "</font>" +
"<br />"
)
);
for details about html tags support in TextViews you can check this link.
You can't directly, the small tag creates a RelativeSizeSpan with a proportion of .8f, which is hardcoded into the implementation of Html.fromHtml.
Leaves two options that I can see, set the text size to 20sp (which would make small work out to 16sp). Probably not ideal.
The other option is to use a custom tag <mySmall> by replacing all occurrences of <small> and </small> with <mySmall>& </mySmall>. And then call fromHtml (String source, Html.ImageGetter imageGetter, Html.TagHandler tagHandler) with a TagHandler that integrates a AbsoluteSizeSpan into the output Editable.
Why don't you use txt.setSizeText(yoursize)? However you can retrieve your dimensions using this:
float yourDimen = getResources().getDimension(R.dimen.your_dimen_name);
i am programming a game with andengine and i am using Andengine Text to display the high score...
Thats the code:
StrokeFont mFont = FontFactory.createStrokeFromAsset(this.getFontManager(), mainFontTexture, this.getAssets(), "Roboto-BoldItalic.ttf", 100, true, Color.WHITE, 2, Color.BLACK);
mFont.load();
text_score_menu = new Text(25, 25, mFont, "Score: ",getVertexBufferObjectManager());
if(LC.Score>Constants.highScore){
prefs.edit().putInt("highScore",LC.Score).commit();
text_score_menu.setText("New High: " + LC.Score);
}else{
text_score_menu.setText("Score: " + LC.Score);
}
Problem is that when there is new high score i am getting a new exception exactly here:
text_score_menu.setText("New High: " + LC.Score);
but i dont have that problem when the score is not new highscore and score is display with
text_score_menu.setText("Score: " + LC.Score);
here is the error message:
FATAL EXCEPTION: UpdateThread
java.lang.ArrayIndexOutOfBoundsException: length=210; index=210
at org.andengine.entity.text.vbo.HighPerformanceTextVertexBufferObject.onUpdateVertices(HighPerformanceTextVertexBufferObject.java:121)
at org.andengine.entity.text.Text.onUpdateVertices(Text.java:335)
at org.andengine.entity.text.Text.setText(Text.java:223)
this is a common pitfall with text in AndEngine - when you instantiated the text_score_menu entity, you set the max length then. Try changing this
text_score_menu = new Text(25, 25, mFont, "Score: ",getVertexBufferObjectManager());
to
text_score_menu = new Text(25, 25, mFont, "New High: 123456789",getVertexBufferObjectManager());
that will establish a long enough text field - then be sure to "set" the proper text before showing the entity - (as you are doing in the code you presented)
Is it possible change size of temperature?
remoteViews.setTextColor(R.id.battery, Color.WHITE);
remoteViews.setTextViewText(R.id.battery, String.valueOf((int)batteryLevel + "%" + "|" + temperatura + "°C"));
Batterylevel and temperature are in the same textview. I want change size only of temperature. Actually is 50dp. I want 20dp.Hopw can i do it?
You can change the size using HTML code, but I don't think it is possible to specify detailed sizes in dp with it.
In your case I would use the tag <small> for the temperature:
remoteViews.setTextColor(R.id.battery, Color.WHITE);
String styledText = String.valueOf((int)batteryLevel) + "%" + "|" + "<small>" + temperatura + "°C</small>";
remoteViews.setTextViewText(R.id.battery, Html.fromHtml(styledText));
The list of supported tags is described here:
http://www.grokkingandroid.com/android-quick-tip-formatting-text-with-html-fromhtml/
I need to display multiple lines of text in an Alert Dialog. If I use multiple setMessage() methods, only the last setMessage is displayed, as shown below.
final AlertDialog alertDialog = new AlertDialog.Builder(this).create();
alertDialog.setTitle("Statistics:");
alertDialog.setMessage("No. of attempts: " + counter);
alertDialog.setMessage("No. of wins: " + counterpos);
alertDialog.setMessage("No. of losses: " + counterneg);
Is there a way to create a new line for each of these in the dialog? Like using \n in System.print.out(); method.
Thanks!
You can do something like this
String alert1 = "No. of attempts: " + counter;
String alert2 = "No. of wins: " + counterpos;
String alert3 = "No. of losses: " + counterneg;
alertDialog.setMessage(alert1 +"\n"+ alert2 +"\n"+ alert3);
You could just create one string of everything you want to show and add "\n" where you'd like the line breaks to be.
alertDialog.setMessage("No. of attempts: " + counter + "\n" +
"No. of wins: " + counterpos + "\n" +
"No. of losses: " + counterneg);
Or even better to use a StringBuilder:
StringBuilder sb = new StringBuilder();
sb.append("No. of attempts: " + counter);
sb.append("\n");
sb.append("No. of wins: " + counterpos);
sb.append("\n");
sb.append("No. of losses: " + counterneg);
alertDialog.setMessage(sb.toString());
And the best way to do it would be to extract the static texts into a string resource (in the strings.xml file). Use the %d (or %s if you want to insert strings rather than ints) to get the dynamic values in the right places:
<string name="alert_message">No. of attempts: %1$d\nNo. of wins: %2$d\nNo. of losses: %3$d</string>
And then in code:
String message = getString(R.string.alert_message, counter, counterpos, counterneg);
alertDialog.setMessage(message);
You can also insert newlines directly in the strings.xml file:
<string name="my_string_text">This would revert your progress.\n\n Are you sure you want to proceed?</string>
Kotlin simplifies the solution by:
chaining the calls of the set methods
using interpolated strings
as follows:
"AlertDialog.Builder
This Builder object to allow for chaining of calls to set methods
"
(https://developer.android.com/reference/android/app/AlertDialog.Builder)
fun alertDemo() {
var counter: Int = 5
var counterpos: Int = 2
var counterneg: Int = 3
val builder = AlertDialog.Builder(this)
.setTitle("Statistics:")
.setMessage("""
|number of
|
|attempts: $counter
|wins: $counterpos
|losses: $counterneg
""".trimMargin())
.show()
}
I had prepared a screen-shot of the result, but as I am new here, I appear to have learned that uploading screenshots may be restricted to higher level community peers. Or did I miss something? Thank you for enlighting (perhaps not only) myself :)
The screenshot comes in a nice format without showing the bars.
PS:
For the minimalists, due to chaining, we could even eliminate the redundant "val builder ="