2015-08-09 51 views
0

我通過編程創建了大部分按鈕。根據手機的大小,有沒有公式或方法可以調整我的按鈕尺寸?我注意到如果我在用戶界面中創建一個按鈕,並且讓它的高度爲10.它在小型手機或大型手機上看起來差不多,但如果我以編程方式創建此按鈕並將其高度設置爲10,我注意到了它不會爲更大的手機調整大小。換句話說,它在小手機上看起來很棒,但在小手機上很糟糕。 有沒有適當的方法來做到這一點?請參考下面以編程方式設置按鈕尺寸,具體取決於手機的尺寸

LinearLayout ln = new LinearLayout (this); 
Button btn = new Button (this); 
LinearLayout.LayoutParams Lparamters = new LinearLayout.LayoutParam (ViewGroup.LayoutParams.MatchParent, 10); 
ln.AddView (btn, Lparamters); 
+1

你現在怎麼創建它?向我們展示一些代碼。 – iTurki

回答

1

一個簡單的例子,你可以在屏幕的寬度/高度是這樣的:

Display display = ((WindowManager)getSystemService(Context.WINDOW_SERVICE)).getDefaultDisplay(); 
int width = display.getWidth(); 
int height = display.getHeight(); 

然後你可以使用這個特定的寬度分配給您的按鈕。

//First: add your button to your LinearLayout (IMPORTANT Step) 
//Then: get the LayoutParams of your button 
LinearLayout.LayoutParams params = btn.getLayoutParams(); 
//Then: change the width of the button 
params.width = width/2; //or whatever relative size you want. 
//Then set the modefied LayoutParams to your button. 
btn.setLayoutParams(params); 
0

看看Supporting Multiple Screens。用xml定義你的佈局!

res/layout/my_layout.xml    // layout for normal screen size ("default") 
res/layout-large/my_layout.xml  // layout for large screen size 
res/layout-xlarge/my_layout.xml  // layout for extra-large screen size 
res/layout-xlarge-land/my_layout.xml // layout for extra-large in landscape orientation 

把你的按鈕尺寸是適合的顯示尺寸

0

你可以得到的寬度和使用WindowManager高度:

int width = mContext.getWindowManager().getDefaultDisplay().getWidth(); 

一旦你在你的onCreate或任何得到這個寬度,你可以用它來做這樣的事情:

view.findViewById(R.id.icon).setPadding(width/80, width/80, width/80, width/80);   
((LinearLayout.LayoutParams) view.findViewById(R.id.icon).getLayoutParams()).setMargins(width/80, width/80, width/80, width/80);