溫馨提示×

android中setbackground的用法是什么

小億
417
2024-04-08 10:35:37
欄目: 編程語言

在Android中,setBackground()方法用于設(shè)置View(視圖)的背景。這個(gè)方法接受一個(gè)Drawable對象作為參數(shù),可以是顏色、圖片或者是自定義的Drawable對象。通過設(shè)置背景,可以改變View的外觀和樣式。

示例代碼:

// 設(shè)置背景顏色
view.setBackground(new ColorDrawable(Color.RED));

// 設(shè)置背景圖片
view.setBackground(ContextCompat.getDrawable(context, R.drawable.background_image));

// 設(shè)置自定義Drawable對象
view.setBackground(new CustomDrawable());

需要注意的是,setBackground()方法在Android API 16(Android 4.1)及以上版本中可用。如果需要支持更舊的Android版本,可以使用setBackgroundDrawable()方法。

0