android中的回調舉例:在surfaceview中結束宿主activity

來源:互聯網
上載者:User

背景
SurfaceView是遊戲開發中經常使用到的View,能夠即時的更新UI介面,實現遊戲邏輯。在這裡的討論中,我設定了一個GameActivity , 在這個activity的布局中,放置了一個全屏的GameSurfaceView。GameActivity雖然是遊戲的主體,但遊戲的邏輯和顯示都是由GameSurfaceView負責。遊戲開始後,GameSurfaceView在新開的線程中運行,並即時的更新遊戲介面。
當遊戲邏輯結束時,需要結束掉activity,以使得activity stack順序清晰。特別是在2.2系統下,不能一次性關閉app,只能每次都關閉掉各個acticity。

實現
如何在GameSurfaceView中結束掉這個activity呢?
增加回調介面,在GameSurfaceView中實現回調!
關於回調的介紹: callback。
1,設定一個回調介面
 
public interface OnEndOfGameInterface { 
    public void onEndOfGame(); 
     

在GameActivity中實現這個介面。
 
public class GameActivity extends Activity implements OnEndOfGameInterface   { 
//.... 
@Override 
    public void onEndOfGame() {      
        this.finish(); 
    } 

在GameSurfaceView中定義回調類型的成員。 並定義一個public method 用來設定回調成員為GameActivity。
 
protected OnEndOfGameInterface mOnEndOfGame ; //callback interface 
 
public void setOnEndOfGame(OnEndOfGameInterface xOnEndOfGame){ 
        mOnEndOfGame = xOnEndOfGame; 
    } 
     

GameActivity中,開啟GameSurfaceView的同時,必須調用setOnEndOfGame方法,設定好回調。
view plain
mGameSurfaceView = (ReverseGameSurfaceView) findViewById(R.id.reverse_game_surface_view); 
            mGameSurfaceView.setOnEndOfGame(this);  //傳入this,設定自己為回調目標 
            mGameSurfaceView.setMode(GameBasicSurfaceView.RUNNING); 

如此,當GameSurfaceView結束時,就可以調用onEndOfGame方法,實現回調了!

摘自:BIAOBIAOqi的小巢

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.