[英](Android) Set Width/Height of (Image-)Button in Java Class
我想在Java Class
設置一個ImageButton
的width
和height
,按鈕的width of the display / 4
應該是width of the display / 4
的width of the display / 4
,按鈕的height of the display / 4
應該是height of the display / 4
的height of the display / 4
。
代碼:
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Display display = getWindowManager().getDefaultDisplay();
Point size = new Point();
display.getSize(size);
int width = size.x;
int height = size.y;
ImageButton button = (ImageButton) findViewById(R.id.imageButton);
// button.setWidth(width/4)
// button.setHeight(height/4)
}
顯然沒有名為setWidth()
或setHeight()
的按鈕的方法,那么我該如何完成呢?
不允許我發表評論,但如果您查看 activity_main.xml,您應該會在其中找到類似的內容。
<ImageButton
android:contentDescription="@+id/imageButton1"
android:id="@+id/imageButton1" />
從這里,你可以添加到這個android:layout_width = 50p
,其中 50p 是 50 像素寬。 您可以將其更改為 `android:layout_height = 100p,只需將 50 和 100 更改為您喜歡的數字即可。 所以,在你添加它們之后它看起來像這樣,
<ImageButton
android:contentDescription="@+id/imageButton1"
android:id="@+id/imageButton1"
android:layout_width ="50p"
android:layout_height ="50p" />
如果要從 Java 代碼設置 ImageView 的寬度和高度,可以執行以下操作:
LayoutParams params = button.getLayoutParams();
params.width = width/4;
params.height = height/4;
button.requestLayout();
可能的重量是您要尋找的。 例如這段代碼會給你四個矩形,每個人都占據四分之一的屏幕
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="vertical">
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="1">
<View
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="1"
android:background="@android:color/black"/>
<View
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="1"
android:background="@android:color/white"/>
</LinearLayout>
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="1">
<View
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="1"
android:background="@android:color/holo_red_dark"/>
<View
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="1"
android:background="@android:color/holo_blue_bright"/>
</LinearLayout>
</LinearLayout>
您可以在 linearlayout 中定義 weightSum,並且視圖將縮放為 weightSum 的百分比。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.