set imageview width and height programmatically android

activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/main_layout"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    android:background="#d3d3d3"
    tools:context=".MainActivity">

    <ImageView xmlns:android="http://schemas.android.com/apk/res/android"
        xmlns:tools="http://schemas.android.com/tools"
        android:id="@+id/imageView"
        android:layout_width="50dp"
        android:src="@drawable/ic_png_image"
        android:layout_height="50dp"
        android:layout_margin="20dp"
        android:orientation="vertical"
        tools:context=".MainActivity"/>

    <Button
        android:layout_below="@+id/imageView"
        android:id="@+id/button"
        android:padding="10dp"
        android:layout_margin="10dp"
        android:layout_width="wrap_content"
        android:textAllCaps="false"
        android:textColor="@color/colorWhite"
        android:background="@color/colorPrimary"
        android:text="Click to Change Image Size"
        android:layout_height="wrap_content" />
</RelativeLayout>

MainActivity.java
package com.android.kotlin.changeimagesize;
import android.content.Context;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.content.res.AppCompatResources;
import android.util.TypedValue;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.RelativeLayout;

public class MainActivity extends AppCompatActivity {
    Context context;
    private int dimensionInDP = 200;
    ImageView imageView;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        context = this;
       imageView =(ImageView)findViewById(R.id.imageView);
       Button button =(Button) findViewById(R.id.button);

        button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                int dimensionInDp = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, dimensionInDP, getResources().getDisplayMetrics());
                imageView.getLayoutParams().height = dimensionInDp;
                imageView.getLayoutParams().width = dimensionInDp;
                imageView.requestLayout();
            }
        });
    }
}

No comments:

Post a Comment

Popular Posts