2014-03-03 86 views
0

我想定位水平居中的ViewLayout。我的代碼如下失敗。我怎樣才能解決這個問題?Android:如何將imageView設置爲水平中心

見我的代碼:

LinearLayout LLT = new LinearLayout(context); 
LLT.setOrientation(LinearLayout.VERTICAL); 
LLT.setLayoutParams(new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT)); 

//get booktheme by bookID 
theme = db.getthemeByID(id); 
String themePath = theme.getFilepath(); 
int resid = getResources().getIdentifier(themePath, "drawable", getPackageName()); 
//imageView 
ImageView imageTheme = new ImageView(context); 
imageTheme.setLayoutParams(new LayoutParams(500, 700)); 
imageTheme.setScaleType(ImageView.ScaleType.CENTER_INSIDE); 
imageTheme.setPadding(0, 20, 0, 10); 
imageTheme.setAdjustViewBounds(true); 
imageTheme.setImageResource(resid); 

LLT.addView(imageTheme); 
// add view 
VF.addView(LLT); 

回答

0

使用Gravity功能在LayoutParams如下:

LinearLayout.LayoutParams layoutParams=new LinearLayout.LayoutParams(500, 700); 
layoutParams.gravity=Gravity.CENTER_HORIZONTAL; 
imageTheme.setLayoutParams(layoutParams); 

與此一替換您的代碼,並嘗試:

LinearLayout LLT = new LinearLayout(context); 
    LLT.setOrientation(LinearLayout.VERTICAL); 
    LLT.setLayoutParams(new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT)); 



    //get booktheme by bookID 
    theme = db.getthemeByID(id); 
    String themePath = theme.getFilepath(); 
    int resid = getResources().getIdentifier(themePath, "drawable", getPackageName()); 
    //imageView 
    ImageView imageTheme = new ImageView(context); 
    LinearLayout.LayoutParams layoutParams=new LinearLayout.LayoutParams(500, 700); 
    layoutParams.gravity=Gravity.CENTER_HORIZONTAL; 
    imageTheme.setLayoutParams(layoutParams); 
    imageTheme.setScaleType(ImageView.ScaleType.CENTER_INSIDE); 
    imageTheme.setPadding(0, 20, 0, 10); 
    imageTheme.setAdjustViewBounds(true); 
    imageTheme.setImageResource(resid); 

    LLT.addView(imageTheme); 
    // add view 
    VF.addView(LLT); 
+0

這是最後一次嘗試。 – user3001046

+0

@ user3001046對於任何進一步的問題都是免費的,如果您發現我的答案有用,請將其投票。謝謝 –

0

你嘗試過使用相對佈局而不是線性佈局?

編輯: 如果u要使用相對佈局,

RelativeLayout.LayoutParams layoutParams = 
    (RelativeLayout.LayoutParams)imageview.getLayoutParams(); 
layoutParams.addRule(RelativeLayout.CENTER_HORIZONTAL, RelativeLayout.TRUE); 
imageview.setLayoutParams(layoutParams); 

(沒有BTW測試代碼,但我把它用在我的應用程序,所以這SHLD做的工作之一)

+0

我已經tryed.chang Linearlayout >>> RelativeLayout LLT = new RelativeLayout(context);.同樣輸出 – user3001046

相關問題