2014-10-03 77 views
0

我目前通过XML与整个R.id.x方法用下面的函数添加图片而不是把它们解析XML格式,与前面提到的话题/问题的帮助我搜索以及与此想出了:的Android添加ImageView的编程

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Ç

private Context c; 
private RelativeLayout rl; 

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

上述函数被调用每一个活动的的onCreate()功能和设置UtilLib当前上下文和RelativeLayout进行相应的绘制。

功能ImageRAW()是我想用它来替换旧的图片()功能,使事情更容易为我。我会怎样做到这一点?

+0

我希望findViewById()方法中的ID与setImageResource()方法中的ID不同。图像的ID应该是R.id.x和ImageRAW的东西就像R.drawable.x – Incredible 2014-10-03 17:18:07

+1

你已经创建了一个RelativeLayout,但它是屏幕内容的一部分吗? – Karakuri 2014-10-03 17:36:29

+0

@Incredible是的,对于ImageRAW函数,我提供了一个R.drawable.x – Zubaja 2014-10-03 17:56:27

回答

1

试试你的SetUtilContext()之前补充一点:

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

而且是在结束你的ImageRAW()方法:

menu.addChild(rl); 
+0

你的方法奏效,但我不得不稍微调整一下。 ImageRAW(R.drawable.head,R.id.game,250,100); 这是因为我使用的是tabhost,因此将布局作为直接参数不起作用;所以布局的id必须通过。 – Zubaja 2014-10-12 12:40:55

0

按难以置信的要求,我的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)); 
} 
+0

您正在创建新的RelativeLayout,为其创建新的LayoutParams,将图像添加到此RelativeLayout中,但我无法看到将此RelativeLayout添加到您的活动的位置。 – Incredible 2014-10-04 09:44:23