[英]Android ignoring my setWidth() and setHeight()
那么,為什么這個代碼:
package org.popoffka.apicross;
import android.app.Activity;
import android.os.Bundle;
import android.widget.Button;
public class Game extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Button testButton = new Button(this);
testButton.setBackgroundResource(R.drawable.cell);
testButton.setWidth(20);
testButton.setHeight(20);
setContentView(testButton);
}
}
...產生這個東西: http ://i42.tinypic.com/2hgdzme.png,即使代碼中有setWidth(20)和setHeight(20)? (R.drawable.cell實際上是一個20x20 PNG圖像,包含帶有銀色邊框的白色單元格)
設置View的寬度和高度的正確方法是通過LayoutParams來實現。 請參見ViewGroup.LayoutParams和View.getLayoutParams()。
您將按鈕設置為內容視圖,這意味着您將其用作“根容器”。
您應該將Button添加到適當的布局,然后將布局設置為內容視圖。
想一想,你在按鈕兩側會有什么? 沒有任何組件可以覆蓋該區域,並且UI不可能知道在這些區域呈現什么。
我知道這是一個遲到的答案,但希望它可以幫助某人。
這是因為默認情況下Button的最小寬度為64dip。 在設置寬度之前將其設置為0。
b.setMinimumWidth(0);
否則最佳做法是使用LayoutParams
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.