Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to add a new object to Layout by Java? Android

Tags:

java

android

For example, I have an ImageView got by this:

public ImageView get_image_by_name(String name)
{
    int image_id = getResources().getIdentifier(name , "drawable", getPackageName());
    return (ImageView)findViewById(image_id);
}

Not sure it works at all.

How shall I add it to layout?

like image 512
user2136963 Avatar asked Dec 13 '25 16:12

user2136963


1 Answers

Assuming this function is placed somewhere within Activity, you can try this:

public ImageView get_image_by_name(String name)
{
    int image_id = getResources().getIdentifier(name , "drawable", getPackageName());
    ImageView iv = new ImageView(this);
    ViewGroup.LayoutParams lp = new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
    iv.setLayoutParams(lp);
    iv.setImageDrawable(getResources().getDrawable(image_id));
    return iv;
}

You can also change LayoutParams to meet your requirements.

like image 178
Pavel Dudka Avatar answered Dec 15 '25 05:12

Pavel Dudka