Skip to main content

How to create an ImageView programmatically in Android


Create An ImageView Programmatically




The ImageView element displays an image to its visible area. Android app developers can simply add an ImageView tag and available attributes to their XML layout file to show an ImageView to the android app user interface. In this XML layout file, they can set the ImageView image source by using its src attribute. This is a simple job.




But sometimes, android app developers want to add an ImageView widget programmatically to their android application. So they have to write a few lines of code to their java or kotlin programming file to achieve this. This android app development tutorial will demonstrate to us how can we add an ImageView widget to our android application dynamically and set an image source to display it.




Though the following code snippets are very clear to understand the full scenario, we will describe here the code. To add an ImageView programmatically to the layout we first add a relative layout in the XML layout file. Then we will put a Button widget inside it. On the Button click event, we will add the ImageView inside the relative layout programmatically.




Inside the Button click event, we will call ImageView() method to create an instance of a new ImageView widget. Then we will call Imageview setImageDrawable() method to add a drawable image source to the ImageView widget.




After that, we will create a LayoutParams object to define the newly created ImageView layout parameters such as width and height. In this layout parameters object, we will add a rule to put ImageView widget below of Button widget inside the relative layout. Then we will apply this layout parameters object to the ImageView widget.




Finally, we add the newly created ImageView object to the relative layout using the addView() method. Now our android app will create an ImageView programmatically on the Button click event and display an image on it.



activity_main.xml



<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/rl"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:padding="10dp"
tools:context=".MainActivity"
android:background="#bfbbb1"
>
<Button
android:id="@+id/btn"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Create ImageView"
/>
</RelativeLayout>





MainActivity.java



package com.cfsuman.androidtutorials;

import android.os.Bundle;
import android.app.Activity;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.RelativeLayout.LayoutParams;
import androidx.core.content.ContextCompat;


public class MainActivity extends Activity {

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);

// Get the context
MainActivity context = this;

// Get the widgets reference from XML layout
final RelativeLayout rl = (RelativeLayout) findViewById(R.id.rl);
final Button btn = (Button) findViewById(R.id.btn);

btn.setOnClickListener(view -> {
// Initialize a new ImageView widget
ImageView iv = new ImageView(getApplicationContext());

// Set an image for ImageView
iv.setImageDrawable(
ContextCompat.getDrawable(
context,
R.drawable.flower_small
)
);

// Create layout parameters for ImageView
LayoutParams lp = new LayoutParams(
LayoutParams.WRAP_CONTENT,
LayoutParams.WRAP_CONTENT
);

// Add rule to layout parameters
// Add the ImageView below to Button
lp.addRule(RelativeLayout.BELOW, btn.getId());

// Add layout parameters to ImageView
iv.setLayoutParams(lp);

// Finally, add the ImageView to layout
rl.addView(iv);
});
}
}








Popular posts from this blog

Restricting Jetpack Compose TextField to Numeric Input Only

Jetpack Compose has revolutionized Android development with its declarative approach, enabling developers to build modern, responsive UIs more efficiently. Among the many components provided by Compose, TextField is a critical building block for user input. However, ensuring that a TextField accepts only numeric input can pose challenges, especially when considering edge cases like empty fields, invalid characters, or localization nuances. In this blog post, we'll explore how to restrict a Jetpack Compose TextField to numeric input only, discussing both basic and advanced implementations. Why Restricting Input Matters Restricting user input to numeric values is a common requirement in apps dealing with forms, payment entries, age verifications, or any data where only numbers are valid. Properly validating input at the UI level enhances user experience, reduces backend validation overhead, and minimizes errors during data processing. Compose provides the flexibility to implement ...

jetpack compose - TextField remove underline

Compose TextField Remove Underline The TextField is the text input widget of android jetpack compose library. TextField is an equivalent widget of the android view system’s EditText widget. TextField is used to enter and modify text. The following jetpack compose tutorial will demonstrate to us how we can remove (actually hide) the underline from a TextField widget in an android application. We have to apply a simple trick to remove (hide) the underline from the TextField. The TextField constructor’s ‘colors’ argument allows us to set or change colors for TextField’s various components such as text color, cursor color, label color, error color, background color, focused and unfocused indicator color, etc. Jetpack developers can pass a TextFieldDefaults.textFieldColors() function with arguments value for the TextField ‘colors’ argument. There are many arguments for this ‘TextFieldDefaults.textFieldColors()’function such as textColor, disabledTextColor, backgroundColor, cursorC...

jetpack compose - Image clickable

Compose Image Clickable The Image widget allows android developers to display an image object to the app user interface using the jetpack compose library. Android app developers can show image objects to the Image widget from various sources such as painter resources, vector resources, bitmap, etc. Image is a very essential component of the jetpack compose library. Android app developers can change many properties of an Image widget by its modifiers such as size, shape, etc. We also can specify the Image object scaling algorithm, content description, etc. But how can we set a click event to an Image widget in a jetpack compose application? There is no built-in property/parameter/argument to set up an onClick event directly to the Image widget. This android application development tutorial will demonstrate to us how we can add a click event to the Image widget and make it clickable. Click event of a widget allow app users to execute a task such as showing a toast message by cli...