How to Dynamically Create and Add Imageview to LinearLayout in Android

In android programming, we can dynamically create an ImageView and add it to a layout programmatically using the example code below.

Please note that both the ImageView and LinearLayout are dynamically created. This might be different from your use case but in generally it will give you an insight on how to solve the problem.

import android.os.Bundle;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;

public class AddImageView extends AppCompatActivity {

    protected void onCreate(@Nullable Bundle savedInstanceState) {

        LinearLayout linearLayout = new LinearLayout(getApplicationContext());
        linearLayout.setLayoutParams(new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT));

        //Add Imageview
        ImageView imageView = new ImageView(getApplicationContext());
        imageView.setLayoutParams(new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT));


If you have any questions or suggestions kindly use the comment box or you can contact us directly through our contact page below.


Add a Comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.