[英]Change background color of another activity with button
I have two activities main and settings.我有两个主要活动和设置。 I want to change the background color of the main using a button that's on settings.
我想使用设置上的按钮更改主体的背景颜色。 I tried using RelativeLayout and get the layout of the main using the id and changing the color when touching the button but it doesn't work.
我尝试使用 RelativeLayout 并使用 id 获取主要布局并在触摸按钮时更改颜色但它不起作用。 I also tried doing with Intent but I don't know how to do it.
我也尝试过使用 Intent 但我不知道该怎么做。 Got the code for the settings activity below
获得了下面设置活动的代码
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);
}
});
}
}
Any help please?有什么帮助吗?
You cannot change views of another activity like that.您不能像那样更改其他活动的视图。
You can send an 'extra' parameter with your Intent and read it on Settings activity.您可以发送带有 Intent 的“额外”参数,并在“设置”活动中读取它。 You can change the color based on the value you receive via the intent.
您可以根据通过意图收到的值更改颜色。
Or if its a more permanent setting, you can save it on SharedPreferences and read it on Main.或者,如果它是一个更永久的设置,您可以将其保存在 SharedPreferences 上并在 Main 上阅读。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.