【问题标题】:Android Studio, Change the color of the background by pressing a switch button [duplicate]Android Studio,通过按开关按钮更改背景颜色[重复]
【发布时间】:2020-11-12 04:35:19
【问题描述】:

刚开始在 Android Studio 中工作,对于大多数事情,我可以用“Google it”找到一切都很好,但显然对于这件事我没有。我有一个基本的开关按钮,我想将应用程序颜色背景从白色更改为黑色,然后取消选中该按钮。询问非常简单,将开关的文本从“黑暗模式”更改为“白色模式”就可以了。 询问在 MainActivity.java 中完成。

final Switch BackgroundColorButton = (Switch) findViewById(R.id.BackgroundColorButton);
            BackgroundColorButton.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    if(BackgroundColorButton.isChecked())
                    {
                        BackgroundColorButton.setText("White Mode");
                        //here I need to change the app background color to Black or DarkGray
                    }
                    else
                    {
                        BackgroundColorButton.setText("Dark Mode");
                         //here I need to change the app background color to White
                    }
                }
            });

【问题讨论】:

    标签: java android android-studio


    【解决方案1】:

    好的,确实在印度视频中找到。 简短的解决方案,使用 //JUST THIS

    添加活动主 XML 代码行
    <?xml version="1.0" encoding="utf-8"?>
    <androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
        xmlns:app="http://schemas.android.com/apk/res-auto"
        xmlns:tools="http://schemas.android.com/tools"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:id="@+id/rView" // JUST THIS
        tools:context=".MainActivity">
    

    在mainactivity.java中

    final Switch BackgroundColorButton = (Switch) findViewById(R.id.BackgroundColorButton);
                BackgroundColorButton.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        if(BackgroundColorButton.isChecked())
                        {
                            BackgroundColorButton.setText("White Mode");
                            screenView.setBackgroundColor(Color.BLACK);//JUST THIS
    
                        }
                        else
                        {
                            BackgroundColorButton.setText("Dark Mode");
                            screenView.setBackgroundColor(Color.WHITE);//JUST THIS
                        }
                    }
                });
    

    【讨论】:

      猜你喜欢
      • 2021-07-05
      • 2012-04-25
      • 2014-08-04
      • 2016-04-05
      • 1970-01-01
      • 2015-06-04
      • 1970-01-01
      • 2013-06-02
      相关资源
      最近更新 更多