Changing text of TextView based on its size - android

Is there any simple way of changing the text of a TextView in order to make it fit the view's size? Note that I do not want to truncate the text or to put an ellipsis, I want to set a different text.
For example instead of Experience: I want to use Exp: if the view is too small(where both those strings are resources).
I know that I could "avoid" this writing a custom .xml layout file for every possible screen size, but I'd like to avoid this if possible. I'm already using some different layout files, but only for situations where the layout needs some radical change to fit the size of the screen. Also in some circumstances I'd like to be able to dynamically set the text of a TextView and this can't be done via xml layout files.
I'm interested only in single-line TextViews and width.
The only way I could think of is to use a custom TextView subclass that uses a fallback text if the original text doesn't fit, but I wonder whether there is a simpler solution and, eventually, how can I reliably compute whether some text fits the TextView size or not.

You can try something like this:
Display display = getWindowManager().getDefaultDisplay();
Point size = new Point();
display.getSize(size);
int screenWidth = size.x;
if( textView.getWidth() > screenWidth ) {
textView.setText("Exp:");
} else {
textView.setText("Experience:");
}
I'm not sure if you need to use getWidth() or getMeasuredWidth() so if it will not work, try second option.

Related

Android: getting width available within layout

I'm wondering whether there is a way to find out the space available for Views within a layout.
To be a little more precise: in the activity two TextViews are displayed side by side. As the second one contains pretty much text, I'd like to check, whether this text can be displayed on the screen or whether it's too large. If that's the case I'll display a smaller version of the text instead (as Android doesn't display this text on multiple lines by default).
Currently I'm using some code like this:
WindowManager windowManager = (WindowManager) getSystemService(WINDOW_SERVICE);
Display display = windowManager.getDefaultDisplay();
Point screenSize = new Point();
display.getSize(screenSize);
int screenWidth = screenSize.x;
if (tvTitle.getWidth() + tvDescription.getWidth() > screenWidth) {
tvDescrition.setText(getString(R.string.descritption_short));
}
But this doesn't work: the widths normally are smaller than the screen, so the long version is used. But: the text isn't displayed completely, the last words are always missing.
I guess the problem is, that the layout is using a padding and is therefore reducing the space really available.
So how to fix this? Any ideas are extremely welcome :-)
You can measure the width of a text(String) in pixels. Using this method:
Paint.measureText(titleString + descriptionString);
If that exceeds the total screen width - horizontal margin - horizontal padding then you can go for the short description.

Android: Can't make small fontsize on programmatic textviews

I'm using the following method which programatically creates a linearlayout and populates it with two textviews, adds text and then turns it into a drawable that I later use a layer above a shape. However, I've noticed that I can't create a small fontsize - it seems stuck at a minimum size which is relatively.. large, and anything that I specify below that value just seems to make it look increasingly blurry (but still the same size). What could be the reason for this?
This behavior occurs whether or not I used TypedValue.COMPLEX_UNIT_SP.
Edit: This size stays the same even if I specify something ridiculous like:
.setTextSize(TypedValue.COMPLEX_UNIT_SP, 60);
it doesn't get any bigger - it just gets "sharper".
Edit 2: If I specify the top textview as having a very large size, then the smaller I set the second textview, the smaller it becomes - as a ratio (for example, if I set the top at 100 and the bottom at 50 it looks exactly the same as the top at 10 and the bottom at 5). However, in no way can I reduce the size of the top textview.
Edit 3: If I remove one of the textviews, and leave only the other one as a single textview in the layout - I can't change the size at all. I can only make it more or less blurry depending how low I set the number but it will always appear the exact same size on screen.
private Drawable createTextLayer() {
LinearLayout newLinearLayout = new LinearLayout(getContext());
newLinearLayout.setOrientation(LinearLayout.VERTICAL);
newLinearLayout.setGravity(Gravity.CENTER);
LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.MATCH_PARENT);
newLinearLayout.setBackgroundColor(getColor(R.color.somecolor));
newLinearLayout.setLayoutParams(layoutParams);
TextView headlinetv = new TextView(getContext());
TextView bodytv = new TextView(getContext());
headlinetv.setText(headlineText);
headlinetv.setTextSize(7);
headlinetv.setGravity(Gravity.CENTER);
bodytv.setText(bodyText);
bodytv.setTextSize(6);
bodytv.setGravity(Gravity.CENTER);
newLinearLayout.addView(headlinetv);
newLinearLayout.addView(bodytv);
newLinearLayout.setDrawingCacheEnabled(true);
newLinearLayout.measure(MeasureSpec.makeMeasureSpec(0, MeasureSpec.UNSPECIFIED),
MeasureSpec.makeMeasureSpec(0, MeasureSpec.UNSPECIFIED));
newLinearLayout.layout(0, 0, newLinearLayout.getMeasuredWidth(), newLinearLayout.getMeasuredHeight());
newLinearLayout.buildDrawingCache(true);
Bitmap b = Bitmap.createBitmap(newLinearLayout.getDrawingCache());
newLinearLayout.setDrawingCacheEnabled(false);
return new BitmapDrawable(getResources(), b);
}
Change your code to:
textView.setTextSize(TypedValue.COMPLEX_UNIT_SP, 7);
Change the font size of 7 to any font size as you wish.
This turned out to be quite tricky and took me several hours to solve, but I'm posting the answer for anyone else who ends up in a similar situation.
The cause:
The entire drawable layer was the uppermost layer above a shape, and was therefore stretched to the size of the shape no matter what. In order to stretch it to the size of the shape, the largest view was stretched (essentially, the longest textview) and therefore couldn't be enlarged or reduced in size.
The solution:
I defined two more textviews, gave them the longest string by 1 character, and made the textcolor transparent. I would have preferred to give them blank space as content but android refused to measure a textview containing whitespace, so it had to be actual text. I put one textview at the top and one at the bottom and thus the visible text appears perfectly centered and in the correct font size.
Edit:
There turns out to be a better way of doing this. Define the textview as the same size as the shape on which it sits as a layer and define padding around the textview (play around with it to find the minimal amount of padding needed). If you have several textviews, divide the size of the shape by the number of textviews and give each one a fraction.

How can avoid text from being cut off on a button?

I am customizing a button in Android changing its background (using a 9patch png file) and changing its font typeface. I put the button in a RelativeLayout since I need precise positioning and dimensioning of this item in a custom layout. I am doing all this programmatically (from creation to setting and display).
I found this question with the same problem, but the solution will not work for me. I used
continueBtn.setPadding(0,0,0,0);
but the graphical output remains the same. More than half the text is cut off in the view.
An excerpt of the code I am using is the following:
Button continueBtn = new Button(getContext());
p = new RelativeLayout.LayoutParams(width, 45);
p.addRule(CENTER_HORIZONTAL);
continueBtn.setLayoutParams(p);
continueBtn.setTypeface(...);
continueBtn.setTextSize(14);
outerLayout.addView(continueBtn);
continueBtn.setPadding(0, 0, 0, 0);
No matter where I put the setPadding method call, things won't change.
What am I doing wrong? Any ideas?
You are setting a constant height for the button of 45 (pixels, I guess). However, apparently the text you are trying to put in it is taller than the amount of space android will let you use. Make your button taller (by changing the LayoutParams) and it will fit without cutting off. Alternately, use a smaller text size so the text will be shorter and fit.

How to make my android component as size dependent for various display screen sizes?

I am making an android component which allows user to pick date from it. It can be helpful for developer who wants user to select date in his app. In my basic view, I have TextView where date from pop up will be populated into it and I have a button beside TextView. When a User clicks on the button, my component gets popped out and displays Dates. The component gets pops out in a Popup window and shows dates as month view and user also can switch from next-previous months, next-previous years just like we do in Calendar. Check the Image.
http://s15.postimage.org/ujw8py60b/stackoverflow.jpg (Sorry, I couldn't upload an image here because I am not allowed as I am new User here)
Each date is a TextView with the width of 35 and height as 30 set by me. DaysDisplayBar is also of some size set by me. So this component's whole width is 245 and height is around 200. Which is for mobile screen size.
I want to make this component as size dependent for various screen display sizes. For e.g. If it is being viewed on Tablet or Pad, it should be bigger in size than what its size on mobile phone screen. That is, For various displays its size should be changed to some value like max 1/3 of display size or like that something.
What can be the solution for this? According to me, some mathematics is needed here, some formula, equations etc. how about Parabola? Please help, I am dumb in maths totally. Thanks! :D
"Each date is a TextView with the width of 35 and height as 30 set by me. DaysDisplayBar is also of some size set by me. So this component's whole width is 245 and height is around 200. Which is for mobile screen size."
^^ is the problem. Sizes should be defined relative to the layout, not absolute. For example, the calendar has 7 columns (one for each day). Instead of making each one 35px, make each 1/7th of the screen.
SO:
I am assuming a DaysDisplayBar is a row containing 7 TextViews (one for each day). If that is true, why not call it a Week? Either way, The trick is in layout_wieght. Make all elements fill_parent, and all with the same weight of 1. This will evenly distrubate all elements in the parent. In your case, the parent is a DaysDisplayBar.
SO:
set DaysDisplayBar attribute `layout_width="fill_parent"
For each TextViewset attribute layout_width="fill_parent" ANDlayout_weight="1"`
hope that helps!
First of all, make sure you use density pixels (dip) instead of pixels.
Second, you can get the screen width and height, and from there, calculate your component size.
You can get the screen dimensions using the Display class getSize() method:
WindowManager wm = (WindowManager) getSystemService(WINDOW_SERVICE);
Display display = wm.getDefaultDisplay();
Point screenSize = new Point();
display.getSize(screenSize);
int screenWith = screenSize.x;
Or you can get the parent view dimensions:
MarginLayoutParams params = (MarginLayoutParams)parentView.getLayoutParams();
int padding = parentView.getPaddingLeft() + parentView.getPaddingRight();
int margin = params.leftMargin + params.rightMargin;
int measuredWidth = parentView.getMeasuredWidth() - padding - margin;
That way you know how much space you have inside the parent view element for your component.
Remember to convert any hard coded value to dip, you can do it this way:
public static int getDensitySize(float size) {
float density = getResources().getDisplayMetrics().density;
return (int)(density * size);
}
You do all of this from your onMeasure method to set your view size, and later on the onDraw you'll use this measure to draw your component.

Android: scaling a button with a background image

I'm probably just being daft but my Google searches are not working out well.
I have a bunch of buttons i add in code that all have dynamic text. I've set a background image for each of these buttons since the default greybutton doesn't work well for my application.
This works perfectly and when the text size (or content) changes, the button automatically grows to accommodate the expanded text. What doesn't work is that I'd like the button to scale proportionally - i.e. if the background image is round, i'd like it to stay round rather than oval as the button gets bigger.
With an imagebutton, there is a property "Adjust view bounds" that does exactly this but I cant put text on an imagebutton. Is there something equivalent for a regular button?
or am I going about this wrong?
i also tried setting the width of the button in code, but I can't seem to determine the new height (button.getHeight() returns 0)
ok i found one way to do it...
I modified the patch-9 to have its expandable area be the maximum on both axis.
then used the DisplayMetrics like this:
DisplayMetrics metrics = new DisplayMetrics();
getWindowManager().getDefaultDisplay().getMetrics(metrics);
buttonView.setGravity(Gravity.CENTER);
int buttonSize=(int) Math.floor(metrics.density*1.6*fontSize);
buttonView.setWidth(buttonSize);
buttonView.setHeight(buttonSize);
where fontSize is the size of the font in DIP that i'm placing on each button. In this case, since I only have a single letter on each button, i don't need to worry about the text length, but one could obviously tweak this to handle that situation as well.

Categories

Resources