2012-12-25 51 views
0

我需要在佈局中放置多個新的ImageViews。問題在於,一個在另一個之上恰好在相同的位置。雖然我改變了位置,但它只涉及到第一個。他們都在80,80。以編程方式放置兩個ImageViews

RelativeLayout.LayoutParams lp1 = new RelativeLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT); 

    addpPicD(lp1,80,80); 
    addpPicD(lp1,100,100); 
} 

private void addpPicD(LayoutParams lp, int Lan, int Lon) 
{ 

     lp.setMargins(Lan, Lon, 0, 0); 
     ImageView imageView = new ImageView(this); 
     imageView.setImageResource(R.drawable.dot_bl); 
     imageView.setLayoutParams(lp); 
     rel.addView(imageView); 

} 
+0

作爲最終結果,您希望如何放置它們?水平並排?一個在另一個下? – AndroidPenguin

+0

我想讓他們置於他們的位置。一個在80,80,另一個在100,100 – Dim

回答

1

您的問題是,您在第一次創建佈局時設置了layoutparams,然後他們不會按照您認爲的那樣重新創建。

簡單的解決方案。將其更改爲以下代碼,該代碼在我的測試下運行:

RelativeLayout.LayoutParams lp1 = null; 

addpPicD(lp1,80,80); 
addpPicD(lp1,100,100); 
} 

private void addpPicD(LayoutParams lp, int Lan, int Lon) 
{ 
    lp = new RelativeLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT); 
    lp.setMargins(Lan, Lon, 0, 0); 
    ImageView imageView = new ImageView(this); 
    imageView.setImageResource(R.drawable.dot_bl); 
    imageView.setLayoutParams(lp); 
    rel.addView(imageView); 

} 
3

RelativeLayout都有自己的Layout Parameters。要並排放置子視圖或垂直放置子視圖,您需要提供規則。在您添加的每個視圖的佈局參數上使用addRule()

傳遞值如RelativeLayout.BELOW,RelativeLayout.RIGHT_OF等以及您要與之對齊的視圖的id