I have an ImageView in my main.xml file:
<ImageView android:id="@+id/pageImage" android:layout_width="270dp" android:layout_height="45dp" android:layout_alignParentLeft="true" android:layout_alignParentTop="true" android:layout_marginLeft="25dp" android:layout_marginTop="15dp" android:scaleType="fitXY" android:src="@drawable/pageimage" />
What I only need to do is to set the the layout_height
programmatically to another value.
Additionally, I need to set the value in dp. So it is currently 45dp, I'd like to change it to another value in my main activity.
I tried to figure out how to do this using LayoutParams, but I couldn't succeed.
Thanks.
getLayoutParams(); params. width = 120; // existing height is ok as is, no need to edit it imageView. setLayoutParams(params); It looks like it works this way.
If you want to just fit the image in image view you can use" wrap content" in height and width property with scale-type but if you want to set manually you have to use LayoutParams. Layoutparams is efficient for setting the layout height and width programmatically.
button. setLayoutParams(new LinearLayout. LayoutParams(10, 100)); Should have work for you.
I think you want something like this:
ImageView imgView = (ImageView) findViewById(R.id.pageImage); imgView.getLayoutParams().height = 200;
So first we get the ImageView from the XML. Then getLayoutParams() gets you exactly the params you may edit then. You can set them directly there. The same for the width etc.
About the unit (sp,dp...) I found something here. Hope this helps:
Use DIP, SP metrics programmatically
There they mention, that all units are pixels. In the example he sets the minimum width of 20sp like this:
TextView tv0 = new TextView(this); int px = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_SP, 20, getResources().getDisplayMetrics()); tv0.setMinimumWidth(px);
P.S. Here is the complete code I use. Hopefully this is what you want:
package com.example.testproject2; import android.os.Bundle; import android.app.Activity; import android.view.Menu; import android.widget.ImageView; public class MainActivity extends Activity { @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); ImageView imgView = (ImageView) findViewById(R.id.pageImage); imgView.getLayoutParams().height = 500; } @Override public boolean onCreateOptionsMenu(Menu menu) { getMenuInflater().inflate(R.menu.activity_main, menu); return true; } }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With