0

So basically I have a button in my MainActivity

 Button button1 = (Button)findViewById(R.id.button1);
 button1.setVisibility(View.GONE);

What is the way to change my button visibility from my GameView class?

if(state == State.PAUSED){
//change button visibility
}
1
  • what is GameView? a fragment?
    – Lino
    May 1, 2016 at 15:35

4 Answers 4

0

The most recommended way to achieve this is to have a local BroadcastReceiver (Sub-class of MainActivity) which will read message from a broadcast, and according to that set the visibility of the button.

And

Send broadcast form the GameView with the proper message.

Seems pretty complicated but trust me, its the best and recommended way to do it.

Link for the tutorial.

0

You need to make public static field Button button1;

And if you want to call button in another class just call that class and button like example

FirstClass.button1

3
  • static fields aren't the recommended way to do it May 1, 2016 at 15:46
  • why it isn't recommended?
    – GlacialMan
    May 1, 2016 at 16:59
  • 1
    Android coding standards say so. Once the Activity is killed by the OS, or the View is no longer needed and can be garbage collected, it'll be null, so you get a NullPointerException when using this approach. It's better to define a method on the activity to act on its button and pass around the activity itself instead of exposing view variables to external classes May 1, 2016 at 17:03
0

Try to keep a reference to the view ( The button ) you want to change , and change it in any way you see fit

button1.setVisibility(View.GONE);

or
button1.setVisibility(View.VISIBLE);
0

Declare your Button button1 as static global variable in MainActivity like

public Static Button  button1; 

then your GameView code will be

if(state == State.PAUSED){
  MainActivity.button1.setVisibility(View.GONE)
}
5
  • 1
    Static variables aren't the recommended way to do it, though May 1, 2016 at 15:48
  • I know that @cricket_007. LocalBroadcast Receiver is the best solution. but I gave him an instant solution.
    – Masum
    May 1, 2016 at 15:50
  • When I am trying to find it by id i get this error: Cannot make a static reference to the non-static method findViewById(int) from the type Activity.
    – Sadboy
    May 1, 2016 at 15:51
  • I think your visibility changing code in a non static method. If it is make that method static also.
    – Masum
    May 1, 2016 at 15:53
  • It works fine, but how do I set an onClickListener without findViewById for my button now?(In xml file a have a button with id button1)
    – Sadboy
    May 1, 2016 at 16:04

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.