0

I want to make the height of a dynamically created TextView to be 50dp. I tried making a dimens.xml file with the code

<dimen name="imageview_height">50dp</dimen>

And then I use

int pixels = getResources().getDimensionPixelSize(R.dimen.imageview_height);

and finally on the generated TextView I simply use.

textView.setHeight(pixels);

However when I run it, my app crashes and says app name keeps stopping.

Shashanth
  • 4,995
  • 7
  • 41
  • 51
Alex Petev
  • 501
  • 5
  • 19

4 Answers4

1

You can set it with this:

textView.setLayoutParams(new LayoutParams(width, height));

But there are different LayoutParams depending on the layout type. Use the layout that your view is in. Ex: if your view is in a LinearLayout, use LinearLayout.LayoutParams

See this post for more info: Android set height and width of Custom view programmatically

Community
  • 1
  • 1
Kurt Acosta
  • 2,407
  • 2
  • 14
  • 29
1

Android throws exception when either height or width is not set programmatically

RelativeLayout.LayoutParams params = (RelativeLayout.LayoutParams) someLayout.getLayoutParams();
params.height = 130;
someLayout.setLayoutParams(params);

so by the above code, we are getting the layout params of the view itself and then set the height programmatically

emilpmp
  • 1,716
  • 17
  • 32
-1

You can do it using the following

int height = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 5, getResources().getDisplayMetrics());
Waqas Ahmed Ansari
  • 1,683
  • 15
  • 30
  • Since I am still learning, I may be wrong and maybe I am wrong. It's nice gesture to tell the reason for the sake of others' learning to comment the reason of downvote. – Waqas Ahmed Ansari Apr 06 '17 at 09:54
  • I suppose that your answer was downvoted, because it doesn't help to solve the problem. The OP knows how to calculate dp, but struggles with an exception. The correct approach would be to ask for a stacktrace and help to track down the exception. – Zielony May 05 '17 at 09:30
-1

Calculation from dps -> pixel ......

final float scale = getContext().getResources().getDisplayMetrics().density;
int pixels = (int) (dps * scale + 0.5f);

Then set that pixel for programatic use...

Nitin Patel
  • 1,605
  • 13
  • 31