Android以编程方式添加ImageView

时间:2014-10-03 17:05:46

标签: android imageview

我目前通过xml使用整个 R.id.x 方法添加图像,并使用以下函数:

public void Image(int ID, int x, int y){
    ImageView iv = (ImageView) findViewById(ID);
    RelativeLayout.LayoutParams position = new RelativeLayout.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
    position.setMargins(x, y, 0, 0);

    iv.setLayoutParams(position);
}

我编写了一个新功能,以编程方式在屏幕上显示这些图像,而不是用XML解析它们,在我搜索的上述主题/问题的帮助下提出了这个:

public void ImageRAW(int ID, int x, int y){
    ImageView iv = new ImageView(c);
    iv.setImageResource(ID);
    RelativeLayout.LayoutParams position = new RelativeLayout.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
    position.setMargins(x, y, 0, 0);

    iv.setLayoutParams(position);
    rl.addView(iv);
}

但它没有用。我也尝试添加以下行,但无济于事: iv.setVisibility(View.VISIBLE);

关于变量 rl c

private Context c;
private RelativeLayout rl;

public void SetUtilContext(Context context){
    c = context;
    rl = new RelativeLayout(context);
}

在每个Activity的 onCreate()函数中调用上述函数,并设置UtilLib的当前Context和RelativeLayout以进行相应的绘制。

功能 ImageRAW() 是我想要用来替换旧的 Image() 的东西功能,让我的事情变得更轻松。我怎么会这样做?

2 个答案:

答案 0 :(得分:1)

尝试在SetUtilContext()之前添加它:

RelativeLayout menu = findViewById(R.layout.menu);

这在你的ImageRAW()方法结束时:

menu.addChild(rl);

答案 1 :(得分:0)

根据Incredible的要求,我的onCreate功能用于测试功能:

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

    SetUtilContext(this);
    Image(R.id.logo, 0, 0);
    GetScreenSize();

    ImageButton(R.id.start_btn  
                , (screenWidth/2)-(GetImageWidth(R.id.start_btn)/2)     
                , 48+GetImageHeight(R.id.logo));
    ImageButton(R.id.options_btn
                , (screenWidth/2)-(GetImageWidth(R.id.options_btn)/2)   
                , 96+GetImageHeight(R.id.logo)+GetImageHeight(R.id.start_btn));
    ImageButton(R.id.about_btn  
                , (screenWidth/2)-(GetImageWidth(R.id.about_btn)/2)     
                , 144+GetImageHeight(R.id.logo)+(GetImageHeight(R.id.start_btn)*2));
    ImageButton(R.id.exit_btn   
                , (screenWidth/2)-(GetImageWidth(R.id.exit_btn)/2)      
                , 192+GetImageHeight(R.id.logo)+(GetImageHeight(R.id.start_btn)*3));
    PlayAudio(R.raw.theme, true);

    ImageRAW(R.drawable.head, 0, GetImageHeight(R.id.logo));
}