[英]Change the background color of the layout programmatically
Android Studio 0.4.6
minSdkVersion 10
targetSdkVersion 19
我有一個名為ReadingLamp
的活動和一個名為activity_reading_lamp.xml
的Relativelayout。
我正在以編程方式嘗試將布局設置為不同的背景顏色。
在我的onCreate中,將內容視圖設置為此布局。
setContentView(R.layout.activity_reading_lamp);
我嘗試通過執行以下操作獲取根視圖:
mActivityBackground = getWindow().getDecorView().getRootView();
然后在我的應用程序中我想改變顏色,所以我喜歡這樣:
mActivityBackground.setBackgroundColor(Color.parseColor("#0cf5ff"));
但是,上面的行沒有做任何改變背景的事情。
我也試過做以下事情:
mActivityBackground = (RelativeLayout)findViewById(R.layout.activity_reading_lamp);
我的代碼在哪里出錯?
你已聲明, setContentView(R.layout.activity_reading_lamp);
在你的Activity
。 然后,您應該查找要更改背景顏色的視圖。 它必須屬於R.layout.activity_reading_lamp
。
View view = findViewById(R.id.declared_inside_reading_lamp);
然后你可以打電話
view.setBackgroundColor(Color.GREEN)
您必須確保activity_reading_lamp.xml
中的所有布局都具有透明背景
您需要指定需要設置的背景。 例如,您可以為活動的父布局設置id,然后執行以下操作:
RelativeLayout parentLayout = (RelativeLayout)findViewById(R.id."your parent layout id and not your activity name");
parentLayout.setBackgroundColor(Color.TRANSPARENT);
如果您想轉換到新顏色,請嘗試以下操作:
@SuppressLint("NewApi") private void tintColor(View rootView, String newColor) {
// currentColor can be given as a new parameter or set as a field
ColorDrawable[] color = {
new ColorDrawable(Color.parseColor(currentColor)),
new ColorDrawable(Color.parseColor(newColor)) };
TransitionDrawable trans = new TransitionDrawable(color);
int sdk = android.os.Build.VERSION.SDK_INT;
if (sdk < android.os.Build.VERSION_CODES.JELLY_BEAN) {
rootView.setBackgroundDrawable(trans);
} else {
rootView.setBackground(trans);
}
trans.startTransition(ANIMATION_TIME); // ANIMATION_TIME : time in milliseconds
}
代碼接受十六進制顏色字符串。
RelativeLayout rl = (RelativeLayout)findViewById(R.id.your_layout_id);
rl.setBackgroundColor(Color.RED);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.