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.support.annotation.Nullable;
import android.support.v7.app.AppCompatActivity;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;

public class AddImageView extends AppCompatActivity {

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

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

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

        linearLayout.addView(imageView);
        setContentView(linearLayout);
    }
}

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