• After 15+ years, we've made a big change: Android Forums is now Early Bird Club. Learn more here.

Apps onKeyDown problems

aNewGuy

Lurker
Jul 22, 2010
3
0
I'm working on a simple game and I've just added a main menu. The problem is that when i click the "Play" button on my menu, the game launches but it doesn't receive key presses properly. My menu class still receives all key presses unless i press one of the arrow keys. After I press one of the arrow keys my game class starts receiving key presses as I expect it to.

right now the code looks something like this

Code:
public class gameTest extends Activity {
    Board mGameBoard;
    private Handler mHandler;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        
        //setup buttons
        setContentView(R.layout.main);
        final TextView btnPlay = (TextView) findViewById(R.id.mainMenuPlay);
        btnPlay.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {
                Log.d("main", "button clicked");
                setContentView(mGameBoard);
                mHandler.post(update);
            }
        }); 
        
        mGameBoard = new Board(this);
        mGameBoard.create();
        
        mHandler = new Handler();
    }
    
    private Runnable update = new Runnable() {
        public void run() {
            mWorld.update();
            mHandler.postDelayed(update, (long) (mGameBoard.timeStep*1000));
        }
    };
}
If i remove the button listener and just skip straight to the game view at works as expected ie:

Code:
public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        
        //setup buttons
        setContentView(R.layout.main);
        /*
        final TextView btnPlay = (TextView) findViewById(R.id.mainMenuPlay);
        btnPlay.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {
                Log.d("main", "button clicked");
                setContentView(mGameBoard);
                mHandler.post(update);
            }
        }); 
        */
        mGameBoard = new Board(this);
        mGameBoard.create();
        setContentView(mGameBoard);
        mHandler.post(update);
        
        mHandler = new Handler();
    }
That makes the game catch all key presses fine (though, obviously no menu at the start). The game board class just uses a onkeydown() to catch key press events.

This is my first time working on android so i'm not sure about quite a few things. Anyone know what might be wrong? If you need more info just ask.
 

BEST TECH IN 2023

We've been tracking upcoming products and ranking the best tech since 2007. Thanks for trusting our opinion: we get rewarded through affiliate links that earn us a commission and we invite you to learn more about us.

Smartphones