ImageView背景在onResume时被压缩为最后一种尺寸
lateinit var bgImage: NinePatchDrawable
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_test_easy)
bgImage = ContextCompat.getDrawable(this, R.drawable.tm_bg_special) as NinePatchDrawable
iv1.background = bgImage
iv2.background = bgImage
iv3.background = bgImage
iv4.background = bgImage
// It works fine if I use drawable directly to each imageView
iv1.background = ContextCompat.getDrawable(this, R.drawable.tm_bg_special) as NinePatchDrawable
iv2.background = ContextCompat.getDrawable(this, R.drawable.tm_bg_special) as NinePatchDrawable
iv3.background = ContextCompat.getDrawable(this, R.drawable.tm_bg_special) as NinePatchDrawable
iv4.background = ContextCompat.getDrawable(this, R.drawable.tm_bg_special) as NinePatchDrawable
}
如果我直接对每个imageView使用drawable,但它想存储Drawable,因为它在运行时在原始情况下会被读取,并且需要设置为大量imageView,所以它可以正常工作
视觉上发生了什么...
参考xml
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="@color/colorPrimary"
android:orientation="horizontal"
android:layout_margin="5dp"
android:visibility="visible"
android:layout_alignParentBottom="true">
<ImageView
android:id="@+id/iv1"
android:layout_width="90dp"
android:padding="0dp"
android:layout_height="wrap_content"/>
<ImageView
android:id="@+id/iv2"
android:layout_width="50dp"
android:padding="0dp"
android:layout_gravity="center"
android:layout_height="wrap_content"/>
<ImageView
android:id="@+id/iv3"
android:layout_width="120dp"
android:padding="0dp"
android:layout_gravity="center"
android:layout_height="wrap_content"/>
<ImageView
android:id="@+id/iv4"
android:layout_width="20dp"
android:padding="0dp"
android:layout_gravity="center"
android:layout_height="wrap_content"/>
</LinearLayout>
最佳答案
我认为,尽管系统将bgImage设置为视图,但它将调整bgImage本身的大小。这意味着bgImage将使用最后分配给它的视图的大小。
您可以试试看所有图像是否变大:
iv4.background = bgImage
iv3.background = bgImage
iv2.background = bgImage
iv1.background = bgImage
在这种情况下,您可以创建四个NinePatchDrawable并重用它们。