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.
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
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
您可以使用以下方法进行操作
int height = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 5, getResources().getDisplayMetrics());
final float scale = getContext().getResources().getDisplayMetrics().density;
int pixels = (int) (dps * scale + 0.5f);
Then set that pixel for programatic use...
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.