我想創建一個具有固定高度和寬度的自定義 ImageView。
使用 XML 很容易,比如
<ImageView
android:layout_width="20dp"
android:layout_height="20dp"/>
但是如何以編程方式做到這一點?
class customView : ImageView {
// code to achieve fixed height and width
}
uj5u.com熱心網友回復:
您將希望使用您想要使用的 AppCompat 版本,例如 AppCompatImageView 作為 layoutParams 將被支持。我也看到錯誤的一件事:您必須在類的建構式中指定背景關系和所有包含的屬性:
(context : Context, attrs : AttributeSet)
這些將由作業系統自動分配,因此無需對它們進行任何處理,但它們必須存在。這是我為您準備的:
class CustomImageView(context: Context,
attrs : AttributeSet) : AppCompatImageView(context, attrs) {
init {
applyDefaults()
}
private fun applyDefaults(){
val height = 130
val width = 300
layoutParams = ViewGroup.LayoutParams(width, height)
}
}
通過從基類獲取當前布局引數,即 AppCompatImageView。然后將布局引數設定為您想要的高度和寬度作為整數。
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/389677.html
