1. 程式人生 > >【android-tips】如何在view中取得activity物件

【android-tips】如何在view中取得activity物件

今天想實現在view中返回上一個activity的功能,想了半天。因為在雖然view是包含於一個activity的,但是直接在view中用this取得的物件不是activity而是這個view,直接寫activity的名字也不行。於是找到了這個方法並附上!

    首先假設,view是在activity A中定義生成的。假設view的類叫做GameView,則在A中得oncreat()裡,一定把activity物件傳到了GameView的建構函式。

gameview=new GameView(this);
   因為在view中,會有建構函式,只要將context傳給新定義的activity,就能在view中操作activity
public GameView(Context context) {
		super(context);
               Activity activity;
               activity=(Activity) context;
}