[英]Change background color of another activity with button
我有兩個主要活動和設置。 我想使用設置上的按鈕更改主體的背景顏色。 我嘗試使用 RelativeLayout 並使用 id 獲取主要布局並在觸摸按鈕時更改顏色但它不起作用。 我也嘗試過使用 Intent 但我不知道該怎么做。 獲得了下面設置活動的代碼
public class Settings extends AppCompatActivity {
private Button changeColorButton;
private RelativeLayout layout;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_settings);
changeColorButton = findViewById(R.id.changeColorButton);
layout = findViewById(R.id.mainLayout);
/** Called when the user taps the Settings button */
changeColorButton.setOnClickListener(new View.OnClickListener(){
@Override
public void onClick(View V){
Intent intent = new Intent(Settings.this, Main.class);
startActivity(intent);
layout.setBackgroundColor(Color.BLUE);
}
});
}
}
有什么幫助嗎?
您不能像那樣更改其他活動的視圖。
您可以發送帶有 Intent 的“額外”參數,並在“設置”活動中讀取它。 您可以根據通過意圖收到的值更改顏色。
或者,如果它是一個更永久的設置,您可以將其保存在 SharedPreferences 上並在 Main 上閱讀。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.