2011-10-07 67 views
4

我需要在屏幕上居中放置一個imageview,但是在編程時不使用XML佈局。如何使用FrameLayout將畫面居中在屏幕上? (使用java代碼)

我實際上使用了一個FrameLayout,但我不知道如何將它置於FrameLayout上。

這是代碼,我到現在爲止:

 FrameLayout fl = new FrameLayout(this.getApplicationContext()); 
    splash = new ImageView(getApplicationContext()); 
    splash.setImageResource(R.drawable.logo); 
    splash.setLayoutParams(new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT)); 
    fl.addView(splash); 
    fl.setBackgroundColor(Color.BLACK); 
    setContentView(fl); 

回答

4

我想這應該這樣做:

fl.setForegroundGravity(Gravity.CENTER); 
+0

- 中心不能被解析爲一個 \t可變 \t - 重力不能得到解決或是 \t不是一個場 – NullPointerException

5

我想這樣的事情會得到它爲你做:

LayoutParams centerParams = new LayoutParams(LayoutParams.FILL_PARENT,LayoutParams.FILL_PARENT); 

    centerParams.gravity = Gravity.CENTER; 
    fl.setLayoutParams(centerParams); 

check out this page for more info

+0

我上行「centerParams.gravity」錯誤--->重力不能得到解決,或者不是一個字段 – NullPointerException

+0

您導入了哪個LayoutParams類? – FoamyGuy

2

Imageview沒有重力。它具有layout_gravity。

相關問題