AndreaNobili AndreaNobili - 3 months ago 7
Android Question

How can I specify that this ImageView have to be shown smaller?

I am absolutly new in Android development and I am findig the following problem working on my first app.

My problem is related to changing the space occupied by an image into my layout.

So I have a situation like this: I don't put the image directly into my XML layout file but I do it programatically into my activity code calling this method:

ImageView difficultyContainerImageView1 = (ImageView) rootView.findViewById(R.id.difficultyContainer);

difficultyContainerImageView1.setImageDrawable(new BitmapDrawable(getResources(), ImgUtility.createRankingImg(context, 3)));


So the ImgUtility.createRankingImg(context, 3) return a Bitmap object that is setted into the ImgeView of my layout having difficultyContainer as ID.

It works fine and the image is showed into my layout, this one:



<ImageView
android:id="@+id/imageView1"
android:layout_width="fill_parent"
android:layout_height="250dp"
android:scaleType="fitXY" />

<TextView
android:id="@android:id/text1"
style="@style/pastaTitleTextStyle" />

<LinearLayout
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">

<LinearLayout
android:layout_width="0px"
android:layout_height="wrap_content"
android:layout_weight="1"
android:orientation="vertical">

<TextView
style="@style/HeaderTextStyle"
android:text="Difficoltà:" />


<ImageView
android:id="@+id/difficultyContainer"
android:layout_width="fill_parent"
android:layout_height="55dp"
android:scaleType="fitXY" />

</LinearLayout>

</LinearLayout>




The image is correctly showed into this ImageView:

<ImageView
android:id="@+id/difficultyContainer"
android:layout_width="fill_parent"
android:layout_height="55dp"
android:scaleType="fitXY" />


The only problem is that doing in this way the image horizontally occupy all the space of the view, this is what I obtained (the image is the last one that contains the chef hats):

enter image description here

It should depends by the fact that I am using android:layout_width="fill_parent" to say that the ImageView having id=difficultyContainer have to horizontally occupy all the spac of its container (the main LinearLayout).

So I want know how can I set a percentual width\height for this ImageView.

What is the best way to specify a percentage so my image will be shown smaller in my app? What is the best solution to do it?

Answer

Are you trying to ask how to set the size of the imageView programmatically?

If so use:

ImageView imageView = findViewById(R.id.difficultyContainer);
imageView.getLayoutParams().width = 120;

The same for height, just replace width with height.

This value of '120' being in dp, which means the size of the image will adjust depending on the screen size of the output device, meaning you don't need to utilise percentages like you would in html/css

Comments