Joe Hackerberg
Joe Hackerberg

Reputation: 467

Problems with setting a background image in Java-Android

First of all, I want to tell you that I'm new here and I'm from Spain and my english level isn't so good, so please... try to understand me haha. Also, you must know that I'm a telematic engineering student and programming is just my favourite hobby. With this info, I just want you to be comprehensive with my question: I know that it's a rookie question and it's worse when I'm pretending to create an Android game... But I'm learning bit by bit.

PROBLEM

The problem that I have is the next one. I want to set a .PNG image in my principal activity called "*activity_principal*". This image has lot of empty space and the background is initially black (due to the theme selected at the beginning I guess). Well, this image has some details in black and them merges with the background colour.

My first solution was trying to set the two backgrounds from the XML corresponding code, but rapidly I realized it was impossible to use it twice in a same layout. So I thought that it would be fixed by the next way: I set the "android:background="@android:color/white"" in the XML file and in the .java file I set the other resource to the background:

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

    RelativeLayout fondo = (RelativeLayout) findViewById(R.layout.activity_principal);
    fondo.setBackgroundResource(R.drawable.prototipoestructurapantalla);
}

I used to use this structure and never had problems but today, trying to do this, I noticed something strange. Due not to find the error, I put two breakpoints at the lines under "setContentView(..." and debugging, when the cursor reached the last code line "fondo.setBack..." the variable "fondo" was "null" and I think that there is the problem, so when I resume the debugging the app crashes...

I hope you can help me. Thank you!

Upvotes: 1

Views: 648

Answers (1)

Bryan Herbst
Bryan Herbst

Reputation: 67259

The problem is that findViewById(R.layout.activity_principal); is going to return null.

You are passing a layout ID (R.layout.activity_principal) instead of a View ID.

It should look something like findViewById(R.id.fondo);.

Upvotes: 1

Related Questions