Welcome to the Treehouse Community

The Treehouse Community is a meeting place for developers, designers, and programmers of all backgrounds and skill levels to get support. Collaborate here on code errors or bugs that you need feedback on, or asking for an extra set of eyes on your latest project. Join thousands of Treehouse students and alumni in the community today. (Note: Only Treehouse students can comment or ask questions, but non-students are welcome to browse our conversations.)

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and a supportive community. Start your free trial today.

Android Build a Simple Android App with Java Improving Our Code Dynamically Changing the Background Color

[Solved] My app crashes when I change the background color

When I try to change the Background Color my App Builds without errors but when I try to run the app it just crashes. Here is the code.

MainActivity.java
package com.withur.facttest;

import android.graphics.Color;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.RelativeLayout;
import android.widget.TextView;

public class MainActivity extends AppCompatActivity {
    // Declare our View variables
    private FactBook factBook = new FactBook();

    private RelativeLayout relativeLayout;
    private TextView factTextView;
    private Button showFactButton;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        relativeLayout = findViewById(R.id.mainLayout);
        factTextView = findViewById(R.id.factTextView);
        showFactButton = findViewById(R.id.showFactButton);
        View.OnClickListener listener = new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                //Update the screen with a new fact
                relativeLayout.setBackgroundColor(Color.RED);
                factTextView.setText(factBook.getFact());

            }
        };
        showFactButton.setOnClickListener(listener);
    }
}

Edit: The issue was that I changed the layout to Constraint and didn't realize.

Hi Codrin. Could you copy/paste the error message you get in your logcat please? (using the "show only selected application" filter). Thanks

Oh Lauren Moineau that helped! I was using by accident ConstraintLayout because Relative Layout was throwing everything in the corner for me.

Awesome Codrin Postu ! I'm glad you fixed it :)