Bedimindtricks
Bedimindtricks

Reputation: 113

Setting button background drawable in different class

I am working on a game for Android and am having a little bit of trouble figuring this out.

I have a main activity and I have a GameView (SurfaceView). I want to change the background image of a button in the MainActivity when an action is taken in GameView.

My MainActivity is an Activity bu the GameView is not an Activity, it is just being called and displayed inside of my MainActivity.

I thought about doing the following:

Main Activity:

public void setNumberLivesPicture(final Drawable background){
        MainActivity.this.runOnUiThread(new Runnable() {     
            public void run() {         
                numberLivesPicture.setBackgroundDrawable(background);     
            } 
         });
    }

GameView:

public class GameView extends SurfaceView{

    int difficulty =  HomePage.getDifficulty();
    int player = HomePage.getPlayer();
    String direction =  MainActivity.getDirection();
    boolean audio = HomePage.getAudio();
    private Drawable bloodspatterdead;
    Button numberLivesPicture;
    Button numberLivesButton;
    MainActivity mAct;


    public GameView(Context context, AttributeSet attributeSet, MainActivity MActivity, Button NumberLives) {
        super(context, attributeSet);
        gameLoopThread = new GameLoopThread(this);
        if (audio == true){
            backgroundNoise.start();
        }       
        getHolder().addCallback(new SurfaceHolder.Callback()
        {

            @Override
            public void surfaceDestroyed(SurfaceHolder holder) {
                boolean retry = true;
                GameLoopThread.setRunning(false);
                while (retry) {
                    try {
                        gameLoopThread.join();
                        retry = false;
                    } catch (InterruptedException e) {}
                }
            }           

            @Override
            public void surfaceCreated(SurfaceHolder holder) {
                createSprites(difficulty);
                GameLoopThread.setRunning(true);
                gameLoopThread.start();
            }

            @Override
            public void surfaceChanged(SurfaceHolder holder, int format,
                    int width, int height) {
            }
        });
    }


    private void checkForEnemyCollision() {

        int x = playerSprite.getPlayerX();
        int y = playerSprite.getPlayerY();

        Rect playerRect = new Rect(x, y, (x + playerSprite.getPlayerWidth()), (y + playerSprite.getPlayerHeight()));
        for (int i = 0; i<sprites.size(); i++)
        {
            Rect zombieSprite = sprites.get(i).getZombieBounds();
            if(zombieSprite.intersect(playerRect))
            {           
       if (justDied == true){         // if you just died, we'll give you a break
                }

                if (justDied == false){

    if (NumberOfLives <= 1){   // if you do not have any extra lives.. you die!

                        if (shieldsActivated >= 1){
                            shieldsActivated--;
                            if (audio == true){
                                shielddestroyed.start();
                            }
                        }

                        if (shieldsActivated == 0)
                        {           

((MainActivity) getContext()).setTextView("THE ZOMBIES ATE YOUR BRAINS!!");

                        if (audio == true){
                            backgroundNoise.stop();
                            youaredeadmessage.start();              
                            }

                        for (int z = 0; z<playerSprites.size(); z++)
                        {
                        playerSprites.remove(z);
                        }
                        alive = false;

                    }
                    }
                    if (NumberOfLives > 1){

                        if (shieldsActivated >= 1){
                            shieldsActivated--;
                            if (audio == true){
                                shielddestroyed.start();
                            }
                        }

                        else if (shieldsActivated == 1){
                            shieldsActivated=0;
                            if (audio == true)
                            {
                                shielddestroyed.start();
                            }
                        }

else if (shieldsActivated == 0){                        
NumberOfLives = NumberOfLives -1;
justDied = true;

if (NumberOfLives == 4){

//Button numberOfLives2 = (Button) findViewById(R.id.numberLivesPicture);
numberLivesPicture = (Button) findViewById(R.id.numberLivesPicture);

((MainActivity) getContext()).setNumberLivesPicture(R.id.numberLivesPicture);                           numberLivesPicture.setBackgroundResource(R.drawable.numberlives4);
                                }

But this did not work :(

EDIT:

I have used this with much success for changing TEXT inside of a TextView but am not sure how I can use a method like this to change backgrounds:

public void setTextView(final String txt){
        MainActivity.this.runOnUiThread(new Runnable() {     
            public void run() {         
                txv.setText(txt);     
            } 
         });
    }

Used with:

((MainActivity) getContext()).setTextView("THE ZOMBIES ATE YOUR BRAINS!!");

Any suggestions would be greatly appreciated!

Upvotes: 0

Views: 689

Answers (2)

Tofeeq Ahmad
Tofeeq Ahmad

Reputation: 11975

I will suggest you way using Object Oriented Methodology. Bring Button reference from Activity to surfaceView class and then Use runUiThread to update background of Button on any condition

public class SurFaceViewClass extends SurfaceView {

Button btnButton;
MainActivity mAct;

public SurFaceViewClass(MainActivity mact, Button btn) {
    super(mact);
    mAct = mact;
    btnButton = btn;
}

@Override
public boolean onTouchEvent(MotionEvent event) {

    // if(yourconnditIOn)
    mAct.runOnUiThread(new Runnable() {

        @Override
        public void run() {
            btnButton.setBackgroundResource(R.drawable.ic_launcher);
        }
    });
    return super.onTouchEvent(event);
}
}

runOnUiThread is necessary as SurfaceView run in its own thread. Now see how you will call it in Activity

    SurFaceViewClass msClass=new SurFaceViewClass(this, yourbttn);

Upvotes: 2

Bharat Sharma
Bharat Sharma

Reputation: 3966

There can be several possible ways. You can use broadcast sender and receiver for you case.

Steps mentioned below:

Step 1: Create a broadcast receiver in your main activity to receive broadcast from your surfaceview.

BroadcastReceiver receiver = new BroadcastReceiver() {

    @Override
    public void onReceive(Context context, Intent intent) {
        if (intent.getAction().equals("update_button")) {
            // UPDATE YOUR BUTTON HERE.
        }
    }
};

Step 2: Register your receiver after creating your broadcast receiver in main activity.

IntentFilter filter = new IntentFilter("update_button");
registerReceiver(receiver, filter);

Step 3: Send broadcast from your surface view to update button.

Intent intent = new Intent("update_button");
// HERE YOU CAN PUT EXTRAS IN  YOUR INTENT
SendBroadcast(intent);

Wherever you have registered your broadcast receiver it will automatically receive broadcast and update your button in main activity. Using above approach you can update your button or any data from any class.

Upvotes: 1

Related Questions