Derive layout param width from textView text length - android

I want to set the width of a textView programmatically. I want the width to vary with the length of the text (value) of the textView. The text of the textView must not wrap. If the text of a textView is "OLA OMO ALARE", how can I use the length of this string (13) to derive the correct value to set lp.width to, in the code below ?
LayoutParams lp = tv.getLayoutParams();
lp.width =
tv.setLayoutParams(lp);
I tried the code below, but the width was not long enough, thus text was auto wrapped in textView.
lp.width = Math.round( tv.getPaint().measureText(tv.getText().toString())) )
Thanks.

1) You have to use Rect instance for this.
2) Then you need to use this in textView's getPaint() and getTextBound() methods which allows you to put your text of the textview.
3) At the end just get width from the Rect instance.
Code is here with all the steps implemented,
I tested this and it works fine. Hope it helps.
TextView textView = new TextView(this);
textView.setText("AALAP");
Rect rect = new Rect();
textView.getPaint().getTextBounds(textView.getText().toString(), 0, textView.getText().length(), rect);
Log.d(TAG, "onCreate: width: "+rect.width());

Use the ViewGroup.LayoutParams.WRAP_CONTENT constant for this.
ViewGroup.LayoutParams params = myTextView.getLayoutParams();
params.width = ViewGroup.LayoutParams.WRAP_CONTENT;
myTextView.setLayoutParams(params);

Related

Create TextView programatically with fixed pixel width and height

I've tried with below code
dTextView = new TextView(getContext());
dTextView.setText(item.getText());
dTextView.setTextSize(8);
dTextView.setTextColor(Color.BLACK);
dTextView.setLayoutParams(new RelativeLayout.LayoutParams((int) measureWidth, (int) measureHeight));
setMargin(dTextView, item);
rootView.addView(dTextView);
still, it is not exact size what I want. These things are the same for CheckBox view as well. I need to draw this view with an exact pinpoint position with size.
Try this way:
dTextView = new TextView(getContext());
dTextView.setText(item.getText());
dTextView.setTextSize(8);
dTextView.setTextColor(Color.BLACK);
RelativeLayout.LayoutParams params=new RelativeLayout.LayoutParams((int) measureWidth, (int)measureHeight));
setMargin(dTextView, item);
rootView.addView(dTextView, params);
Why do you need to do it like this.
You could create a textview component and add it programmatically to your UI with the help of ListView, Recyclerview etc.
Finally, I've created all views (Checkbox, EditText, and TextView) with exact width and height. EditText and TextView was an easy solution:
dEditText = new EditText(getContext());
dEditText.setPadding(10,5,10,5);
dEditText.setTextSize(6);
dEditText.setTextColor(Color.WHITE);
dEditText.setBackgroundColor(Color.GRAY);
RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams(
(int) measureWidth, (int) measureHeight);
dEditText.setLayoutParams(params);
rootView.addView(dEditText);
setMargin(dEditText, item,params);
// set margin of every created view
private void setMargin(View view, TagsItem item,RelativeLayout.LayoutParams layoutParams) {
layoutParams.setMargins(item.getCurrentXPos(), item.getCurrentYPos(), 0, 0);
// Apply the updated layout parameters to TextView
view.setLayoutParams(layoutParams);
}
But when I try to create CheckBox with exact width and height with this procedure it didn't create a view with exact width and height. I need to follow the below code[Need to set the background and set null for setButtonDrawable ]
int states[][] = {{android.R.attr.state_checked}, {}};
int colors[] = {Color.BLACK, Color.BLACK};
dCheckBox = new CheckBox(getContext());
CompoundButtonCompat.setButtonTintList(dCheckBox, new ColorStateList(states, colors));
dCheckBox.setChecked(item.isCheckState());
//dCheckBox.setText("");
dCheckBox.setBackgroundResource(R.drawable.check_box_selector);
dCheckBox.setButtonDrawable(null);
RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams(
(int) measureWidth, (int) measureHeight);
dCheckBox.setLayoutParams(params);
// checkBoxLayout.addView(dCheckBox);
rootView.addView(dCheckBox);
setMargin(dCheckBox, item,params);

set top,bottom padding on textview with wrap_content

viewParams = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT);
viewParams.setMargins(15, 15, 15, 0);
TextView text = new TextView(mContext);
text.setLayoutParams(viewParams);
text.setGravity(Gravity.CENTER_VERTICAL);
text.setPadding(50,50,50,50);
text.setBackground(mContext.getResources().getDrawable(R.drawable.exp_comments));
I want my textview to have top and bottom padding.
I set background with green-rectangular border around the textview.
I set height with wrap_content.
and it means that the border is just above the text.
I want to increase the top and bottom gap between the border and the text.
So, I tried with setPadding() and setPaddingRelative() method.
But it doesn't work....
The setPadding method values is in pixels. You should convert your dp to pixels and then set the padding.
int valueInDp = 50;
Resources r = getResources();
int px = (int) TypedValue
.applyDimension(TypedValue.COMPLEX_UNIT_DIP, valueInDp, r.getDisplayMetrics());
text.setPadding(px,px,px,px);
Change top and bottom padding,
text.setPadding(50,100,50,100);

Dynamically added TextView has zero width and height

I have a programatically created RelativeLayout as shown in code below. The RelativeLayout has same width and height of an EditText and lies above the EditText. I add a programatically created TextView to it with certain width and height.
overlay = new RelativeLayout(context);
overlay.setBackgroundColor(Color.TRANSPARENT); //NO I18N
viewGroup.addView(overlay);
overlay.bringToFront();
RelativeLayout.LayoutParams lp = ((RelativeLayout.LayoutParams) overlay.getLayoutParams());
lp.width = getMeasuredWidth();
lp.height = getMeasuredHeight();
Log.d(TAG, "initOverlay: width " + lp.width + " height " + lp.height);
lp.addRule(RelativeLayout.ALIGN_BOTTOM, R.id.formulaView);
lp.addRule(RelativeLayout.RIGHT_OF, R.id.fxImg);
lp.setMargins(0, ((int) Util.dptopx(context, 1) + getTotalPaddingTop()), 0, ((int) Util.dptopx(context, 1) + getTotalPaddingBottom()));
overlay.setLayoutParams(lp);
setOverScrollMode(OVER_SCROLL_NEVER);
overlay.setOverScrollMode(OVER_SCROLL_NEVER);
overlay.requestLayout();
The first time when the TextView is added, the views are shown with specified width and height. But when i remove the TextView from RelativeLayout and add a new TextView again, the TextView is not being shown. It has zero width and height though i'm setting a width and height. What could possibly be the problem?
TextView
textview = new CustomTextView(edittext.getContext());
Editable editable = edittext.getEditableText();
String spantext = editable.subSequence(startidx, endidx).toString();
float[] location = Util.determineTextViewLocation(startidx, endidx);
textview.setText(spantext);
textview.setTextSize(TypedValue.COMPLEX_UNIT_PX, edittext.getTextSize());
textview.setX(location[0]);
textview.setY(location[1]);
textview.setLayoutParams(new ViewGroup.LayoutParams((int) location[2], (int) location[3]));
textview.setPadding(0, ((int) location[4]), 0, 0);
overlay.addView(textview);
Log.d(TAG, "width "+textview.getWidth()+" height "+textview.getHeight()+" view"+textview);
Edit: The TextView's onMeasure() method is never getting called.
Try below code :
XTextView textView= new XTextView(this);
textView.setLayoutParams(new RelativeLayout.LayoutParams(100,500));
textview.setText("Sample");
textview.setX(location[0]);
textview.setY(location[1]);
textview.setLayoutParams(lp);
overlay.addView(textview);
textview.requestLayout();
Also for overlay don't use getLayoutParams() method. Use
RelativeLayout.LayoutParams lp = new RelativeLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT)
I had the same problem. What fixed it for me was to add the textview to its parent first, then post a runnable to the text view with
textView.post(new Runnable() { ... })
and then set the layout params within that runnable
I know this question is super old but just in case anyone else runs into this problem :)

How to programmatically set the width of the LinearLayout?

Is the source of the slider and the lesson link:
http://www.oodlestechnologies.com/blogs/Facebook-Style-Slide-Menu-In-Android
In this case, the width of the file "left_menu.xml" determined TextView (android:layout_width="260dp")
How do I set the width to "LinearLayout" file "left_menu.xml" depending on the device screen? For example, I want the width of the "LinearLayout" was always 1/3 of the screen device? Or any way to set the width of the TextView 1/3 of the width of the device screen.
To set the LinearLayout or TextView width to 1/3 of the device screen:
first of all get the device screen width:
Display display = getWindowManager().getDefaultDisplay();
Point size = new Point();
try {
display.getRealSize(size);
} catch (NoSuchMethodError err) {
display.getSize(size);
}
int width = size.x;
int height = size.y;
now just create a LayoutParams and set it to the Text:
LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams((int)(width/3),
LinearLayout.LayoutParams.WRAP_CONTENT); // or set height to any fixed value you want
your_layout.setLayoutParams(lp);
// OR
your_textView.setLayoutParams(lp);
LinearLayout linear = (LinearLayout) findViewById(R.id.ll);
LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT);
linear.setLayoutParams(params);
As you can see, you can set Integer values for the LinearLayout.LayoutParams() constructor, like this:
LinearLayout.LayoutParams cellParams = new LinearLayout.LayoutParams(0, 100);
The costructor wants pixels and not dp(Density Pixels), here's a formula to convert PXs from DPs:
(int) (<numberOfDPs> * getContext().getResources().getDisplayMetrics().density + 0.5f)
LinearLayout layout = (LinearLayout)findViewById(R.id.ll);
LayoutParams params = (LayoutParams) layout.getLayoutParams();
params.height = 100;
params.width = 100;
The above answers are correct. I'll just suggest future readers to take a look at their xml layout file and be sure that the LinearLayout element is not using weight attribute. If so, consider updating weight in your LayoutParams object.
Another good practice is to retrieve the layout params object from the view you're trying to adjust, instead of creating one from scratch and having to set all the values.
LinearLayout YOUR_LinearLayout =(LinearLayout)findViewById(R.id.YOUR_LinearLayout)
LinearLayout.LayoutParams param = new LinearLayout.LayoutParams(
/*width*/ ViewGroup.LayoutParams.MATCH_PARENT,
/*height*/ 100,
/*weight*/ 1.0f
);
YOUR_LinearLayout.setLayoutParams(param);
The easy way to do that, set value of layoutParams, and please notice this size is not in DP.
view.layoutParams.width = 400;
view.layoutParams.height = 150;
view.requestLayout();

How to add an ImageView to the center of the screen, by ratio

My code:
Display display = getWindowManager().getDefaultDisplay();
final int width = display.getWidth();
final int height = display.getHeight();
RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams(200,200);
relativeLayout.addView(img1,params);
params.leftMargin = width/2;
params.topMargin = height/2;
setContentView(relativeLayout);
Could somebody help me to fit my img1 to the center of the screen, at every resolution?
I think that the display.getwidth value is not associated with params.leftmargin.
Please instruct me to get the margin value to any use by dividing it.
try this
RelativeLayout.LayoutParams params =new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.WRAP_CONTENT, RelativeLayout.LayoutParams.WRAP_CONTENT);
params.addRule(RelativeLayout.CENTER_IN_PARENT, RelativeLayout.TRUE);
img1.setLayoutParams(params);
relativeLayout.addView(img1);
EDIT : if u want to add more views then u should create layoutparams for every view and use addRule method I m just giving u an example how to place a view under a view u can place that view right , left or above accoridngly change this RelativeLayout.ALIGN_BOTTOM and u can use RelativeLayout.LAYOUT_BELOW instead of RelativeLayout.ALIGN_BOTTOM
p.addRule(RelativeLayout.ALIGN_BOTTOM, ur_view.getId());
if u create it in xml it will be much more easier
if u want to set margin for any view do something like this
p.setMargins(left margin, top margin, right margin, bottom margin);
left margin, top margin, right margin, bottom margin are Integer
value, which value u want to set for ur view

Categories

Resources