简体   繁体   中英

Can't change the background color through java

Im trying to make a settings activity from which the user can change the background color of the main activity... here is my java code, everything with the xml is fine the target activity to change the background to is not the one with the radio buttons

public class SettingsActivity extends AppCompatActivity {


ConstraintLayout loginContainer;
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_settings);
    loginContainer = findViewById(R.id.loginContainer);
}

public void onColorRadioClicked(View view) {
    // Is the button now checked?
    boolean checked = ((RadioButton) view).isChecked();
    RadioButton btn1 = findViewById(R.id.colorRadio1);
    RadioButton btn2 = findViewById(R.id.colorRadio2);
    RadioButton btn3 = findViewById(R.id.colorRadio3);

    // Check which radio button was clicked
    switch(view.getId()) {
        case R.id.colorRadio1:
            if (checked)
                btn2.setChecked(false);
                btn3.setChecked(false);
                loginContainer.setBackgroundColor(getResources().getColor(R.color.wallBack1));
                break;
        case R.id.colorRadio2:
            if (checked)
                btn1.setChecked(false);
                btn3.setChecked(false);
                loginContainer.setBackgroundColor(getResources().getColor(R.color.wallBack2));
            break;
        case R.id.colorRadio3:
            if (checked)
                btn1.setChecked(false);
                btn2.setChecked(false);
                loginContainer.setBackgroundColor(getResources().getColor(R.color.wallBack3));
            break;
    }
}

}

whenever i click a radio button, at first (without trying to change the color) everything worked but now after ive added those lines, everytime i click it crashes saying it couldnt execute method for android:onClick

the error in the Run section

E/AndroidRuntime: FATAL EXCEPTION: main
              Process: com.example.roeie.renote, PID: 2590
              java.lang.IllegalStateException: Could not execute method for android:onClick
                  at android.support.v7.app.AppCompatViewInflater$DeclaredOnClickListener.onClick(AppCompatViewInflater.java:293)
                  at android.view.View.performClick(View.java:5610)
                  at android.widget.CompoundButton.performClick(CompoundButton.java:122)
                  at android.view.View$PerformClick.run(View.java:22260)
                  at android.os.Handler.handleCallback(Handler.java:751)
                  at android.os.Handler.dispatchMessage(Handler.java:95)
                  at android.os.Looper.loop(Looper.java:154)
                  at android.app.ActivityThread.main(ActivityThread.java:6077)
                  at java.lang.reflect.Method.invoke(Native Method)
                  at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:865)
                  at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:755)
               Caused by: java.lang.reflect.InvocationTargetException
                  at java.lang.reflect.Method.invoke(Native Method)
                  at android.support.v7.app.AppCompatViewInflater$DeclaredOnClickListener.onClick(AppCompatViewInflater.java:288)
                  at android.view.View.performClick(View.java:5610) 
                  at android.widget.CompoundButton.performClick(CompoundButton.java:122) 
                  at android.view.View$PerformClick.run(View.java:22260) 
                  at android.os.Handler.handleCallback(Handler.java:751) 
                  at android.os.Handler.dispatchMessage(Handler.java:95) 
                  at android.os.Looper.loop(Looper.java:154) 
                  at android.app.ActivityThread.main(ActivityThread.java:6077) 
                  at java.lang.reflect.Method.invoke(Native Method) 
                  at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:865) 
                  at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:755) 
               Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.support.constraint.ConstraintLayout.setBackgroundColor(int)' on a null object reference
                  at com.example.roeie.renote.SettingsActivity.onColorRadioClicked(SettingsActivity.java:34)
                  at java.lang.reflect.Method.invoke(Native Method) 
                  at android.support.v7.app.AppCompatViewInflater$DeclaredOnClickListener.onClick(AppCompatViewInflater.java:288) 
                  at android.view.View.performClick(View.java:5610) 
                  at android.widget.CompoundButton.performClick(CompoundButton.java:122) 
                  at android.view.View$PerformClick.run(View.java:22260) 
                  at android.os.Handler.handleCallback(Handler.java:751) 
                  at android.os.Handler.dispatchMessage(Handler.java:95) 
                  at android.os.Looper.loop(Looper.java:154) 
                  at android.app.ActivityThread.main(ActivityThread.java:6077) 
                  at java.lang.reflect.Method.invoke(Native Method) 
                  at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:865) 
                  at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:755) 

The Radio Buttons XML

<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.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"
tools:context="com.example.roeie.renote.SettingsActivity"
android:background="@color/wallBack1">

<RadioButton
    android:onClick="onColorRadioClicked"
    android:id="@+id/colorRadio1"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_marginLeft="16dp"
    android:layout_marginTop="40dp"
    android:text="RadioButton"
    app:layout_constraintLeft_toLeftOf="parent"
    app:layout_constraintTop_toTopOf="parent" />

<RadioButton
    android:onClick="onColorRadioClicked"
    android:id="@+id/colorRadio2"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_marginLeft="16dp"
    android:text="RadioButton"
    app:layout_constraintLeft_toLeftOf="parent"
    app:layout_constraintTop_toBottomOf="@+id/colorRadio1" />

<RadioButton
    android:onClick="onColorRadioClicked"
    android:id="@+id/colorRadio3"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_marginLeft="16dp"
    android:text="RadioButton"
    app:layout_constraintLeft_toLeftOf="parent"
    app:layout_constraintTop_toBottomOf="@+id/colorRadio2" />

</android.support.constraint.ConstraintLayout>

the xml of the activity that needs to be changed is

<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.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:id="@+id/loginContainer"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="@color/wallBack1"
tools:context="com.example.roeie.renote.LoginActivity">

<TextView

    android:id="@+id/textView"
    android:layout_width="350dp"
    android:layout_height="wrap_content"
    android:text="RENOTE"
    android:textAlignment="center"
    android:textColor="@color/fui_bgGoogle"
    android:textSize="80sp"
    app:layout_constraintBottom_toBottomOf="parent"
    app:layout_constraintEnd_toEndOf="parent"
    app:layout_constraintLeft_toLeftOf="parent"
    app:layout_constraintRight_toRightOf="parent"
    app:layout_constraintStart_toStartOf="parent"
    app:layout_constraintTop_toTopOf="parent"
    app:layout_constraintVertical_bias="0.223" />

<Button
    android:id="@+id/signInBtn"
    android:layout_width="230dp"
    android:layout_height="wrap_content"
    android:layout_marginBottom="8dp"
    android:background="@drawable/button_shape_1"
    android:onClick="signInClick"
    android:text="Sign In"
    android:textColor="@color/wallBack1"
    app:layout_constraintBottom_toTopOf="@+id/signOutBtn"
    app:layout_constraintEnd_toEndOf="parent"
    app:layout_constraintLeft_toLeftOf="parent"
    app:layout_constraintRight_toRightOf="parent"
    app:layout_constraintStart_toStartOf="parent"
    app:layout_constraintTop_toTopOf="parent"
    app:layout_constraintVertical_bias="0.977" />

<Button
    android:id="@+id/signOutBtn"
    android:layout_width="230dp"
    android:layout_height="wrap_content"
    android:background="@drawable/button_shape_1_rev"
    android:onClick="signOutClick"
    android:text="Sign Out"
    android:textColor="#FFFFFF"
    app:layout_constraintBottom_toBottomOf="parent"
    app:layout_constraintEnd_toEndOf="parent"
    app:layout_constraintLeft_toLeftOf="parent"
    app:layout_constraintStart_toStartOf="parent"
    app:layout_constraintTop_toTopOf="parent"
    app:layout_constraintVertical_bias="0.928" />

<Button
    android:id="@+id/button2"
    android:layout_width="40dp"
    android:layout_height="40dp"
    android:layout_marginEnd="20dp"
    android:layout_marginTop="28dp"
    android:background="@drawable/ic_action_settings_white"
    android:onClick="settingsBtnClick"
    app:layout_constraintEnd_toEndOf="parent"
    app:layout_constraintTop_toTopOf="parent" />
<!--android:background="@drawable/button_shape_1"-->

wrape your if statement with {}

 switch(view.getId()) {
            case R.id.colorRadio1:
                if (checked){
                    btn2.setChecked(false);
                    btn3.setChecked(false);
                    loginContainer.setBackgroundColor(getResources().getColor(R.color.wallBack1));
                    }
                    break;
            case R.id.colorRadio2:
                if (checked){
                    btn1.setChecked(false);
                    btn3.setChecked(false);
                    loginContainer.setBackgroundColor(getResources().getColor(R.color.wallBack2));
                }
                break;
            case R.id.colorRadio3:
                if (checked){
                    btn1.setChecked(false);
                    btn2.setChecked(false);
                    loginContainer.setBackgroundColor(getResources().getColor(R.color.wallBack3));
                  }
                break;
        }
    }   

your id is missing from the ConstraintLayout in root whose background you want to change.

android:id="@+id/loginContainer"

<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.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"
tools:context="com.example.roeie.renote.SettingsActivity"
android:id="@+id/loginContainer"
android:background="@color/wallBack1">

<RadioButton
    android:onClick="onColorRadioClicked"
    android:id="@+id/colorRadio1"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_marginLeft="16dp"
    android:layout_marginTop="40dp"
    android:text="RadioButton"
    app:layout_constraintLeft_toLeftOf="parent"
    app:layout_constraintTop_toTopOf="parent" />

<RadioButton
    android:onClick="onColorRadioClicked"
    android:id="@+id/colorRadio2"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_marginLeft="16dp"
    android:text="RadioButton"
    app:layout_constraintLeft_toLeftOf="parent"
    app:layout_constraintTop_toBottomOf="@+id/colorRadio1" />

<RadioButton
    android:onClick="onColorRadioClicked"
    android:id="@+id/colorRadio3"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_marginLeft="16dp"
    android:text="RadioButton"
    app:layout_constraintLeft_toLeftOf="parent"
    app:layout_constraintTop_toBottomOf="@+id/colorRadio2" />

</android.support.constraint.ConstraintLayout>

Edit: If you want to change MainActivity background from settings activity then save it in some preference and apply onStart() of the main activity whenever it's active.

Or

You can start your settings activity as startActivityForResult () and then get the background drawable selected in onActivityResult() from intent data and then change it.

EDIT: Sample code

first, start your settings activity like this.

  Intent selectColor = new Intent(this, SettingsActivity.class);
  startActivityForResult(selectColor, 101);

after selection call this method and pass the color id selected

public void setImageSelected(int colorID){
Intent resultIntent = new Intent();
resultIntent.putExtra("SELECTED_COLOR", colorID);
setResult(Activity.RESULT_OK, resultIntent);
finish();
}

and get the result back like this.

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    // Check which request we're responding to
    if (requestCode == 101) {
        // Make sure the request was successful
        if (resultCode == RESULT_OK) {
           //here get the selected id using
           int colorID = data.getIntExtra("SELECTED_COLOR", 0);
          //use it to set the background here
        }
    }
}

To get the background color

int colorSelected = ContextCompat.getColor(this,R.color.selectedColor);

Remove your ids from onColorRadioClicked method

RadioButton btn1 = findViewById(R.id.colorRadio1);
RadioButton btn2 = findViewById(R.id.colorRadio2);
RadioButton btn3 = findViewById(R.id.colorRadio3);

and put it inside OnCreate

In OnCreate method

loginContainer = (ConstraintLayout)findViewById(R.id.loginContainer);
RadioButton btn1 = (RadioButton )findViewById(R.id.colorRadio1);
RadioButton btn2 = (RadioButton )findViewById(R.id.colorRadio2);
RadioButton btn3 = (RadioButton )findViewById(R.id.colorRadio3);

In XML

android:id="@+id/loginContainer"

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM