【问题标题】:Change background color of another activity with button使用按钮更改另一个活动的背景颜色
【发布时间】:2021-11-26 19:52:59
【问题描述】:

我有两个主要活动和设置。我想使用设置中的按钮更改主的背景颜色。我尝试使用 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);
            }
        });
    }
}

有什么帮助吗?

【问题讨论】:

    标签: java xml android-studio


    【解决方案1】:

    您不能像这样更改其他活动的视图。

    您可以在 Intent 中发送一个“额外”参数,并在设置活动中读取它。您可以根据通过 Intent 收到的值更改颜色。

    或者,如果它是一个更永久的设置,您可以将其保存在 SharedPreferences 上并在 Main 上阅读。

    【讨论】:

    • 好的。那么如果可能的话,该 Intent 的代码是什么?
    • 使用 extras 查找活动之间的传递数据。
    • 好的。感谢您的帮助
    猜你喜欢
    • 1970-01-01
    • 2016-03-31
    • 2018-04-29
    • 1970-01-01
    • 2015-06-04
    • 1970-01-01
    • 1970-01-01
    • 2016-01-14
    相关资源
    最近更新 更多