Is it possible to use variables to set the size of a View?

Asked

Viewed 203 times

2

I am beginner in the development and applications and the application I am working in need that the user give me a value (distance in meters) and from this value I will adjust the size of the image to be displayed by the application.
I’m developing in Java with Android Studio.

I thought about doing this using variables that would be used to define my height and width values, for example:

android:layout_width= variavel_w
android:layout_height= variavel_h

but it is not possible to use variables in these fields, or if there would be some other way to adjust the size of my image according to some input. I’ll be very grateful for any help!

1 answer

1


Possible, but not in xml.

You must use the Java object that represents that Imageview and its Layoutparams object.

Get the object from your Imageview:

final ImageView aSuaImageView = findViewById(R.id.aSuaImageView);

Get your Layoutparams object:

//Substitua LinearLayout. por RelativeLayout. se for o caso
LinearLayout.LayoutParams layoutParams = (LinearLayout.LayoutParams) aSuaImageView.getLayoutParams();

Assign the desired values to width and height

layoutParams.width = 100; // Pode usar uma variável
layoutParams.height = 100; // Pode usar uma variável

Assign changed Layoutparams to Imageview:

aSuaImageView.setLayoutParams(layoutParams);

Note:
When programmatically specifying values in Layoutparams, the attributes width and height expect these values to be pixels.
In order to have consistency of dimensions between the various types of canvas, you have to consider the dimensions in dp and convert them to pixels before assigning them to attributes.
Look at this reply how to make the conversion.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.