2013-10-10 112 views
0

我正在創建一個菜單,我想要在所有的活動中。爲此,我創建了一個包含所有按鈕定義和onClickListeners的類。設置後退鍵的按鈕功能

我遇到的問題是定義後退按鈕以充當物理後退按鈕。我創建這個類的方式,它不識別finish()onBackPressed()等..函數。那麼,這樣做的方式是什麼?

public class MenuView extends RelativeLayout { 

private final LayoutInflater inflater; 


public MenuView(Context context, AttributeSet attrs) { 
    super(context, attrs); 

    inflater = (LayoutInflater)context.getSystemService(Context.LAYOUT_INFLATER_SERVICE); 
    inflater.inflate(R.layout.menu_view, this, true); 

    ((ImageView)this.findViewById(R.id.backButton)).setOnClickListener(goBack); 
} 


private final OnClickListener goBack = new OnClickListener() { 
    @Override 
    public void onClick(View v) { 
     //HERE TO INSERT THE WAY TO DO IT 
    } 
}; 
+0

您的回答是正確的,您是對的,但接受的更詳細,所以對我來說更容易理解 – masmic

回答

1

聲明的上下文是一個成員變量,併爲它分配在你的構造是這樣的:

Context context; 

public MenuView(Context context, AttributeSet attrs) { 
    super(context, attrs); 

    this.context = context; 
    inflater = (LayoutInflater)context.getSystemService(Context.LAYOUT_INFLATER_SERVICE); 
    inflater.inflate(R.layout.menu_view, this, true); 

    ((ImageView)this.findViewById(R.id.backButton)).setOnClickListener(goBack); 
    } 

,並在點擊監聽器,你可以添加這行代碼:

((Activity) context).finish(); 

試試吧。希望這會起作用。

0

試試這個,onBackPressed()只需要調用此方法,將工作

private final OnClickListener goBack = new OnClickListener() { 
@Override 
public void onClick(View v) { 
    //HERE TO INSERT THE WAY TO DO IT 

onBackPressed(); 
} 
}; 
+0

'onBackPressed()方法未定義爲類型new View.onClickListener()'。 – masmic

4

應該是足夠的提取context屬性作爲成員變量,並用它在聽衆喜歡((Activity) context).finish()

1

要完成當前可見的Activity,您需要參考它。

試試看,

public class MenuView extends RelativeLayout { 

private final LayoutInflater inflater; 
private Activity mActivity; 

public MenuView(Context context, AttributeSet attrs) { 
    super(context, attrs); 
    mActivity = (Activity)context; 
    inflater = (LayoutInflater)context.getSystemService(Context.LAYOUT_INFLATER_SERVICE); 
    inflater.inflate(R.layout.menu_view, this, true); 

    ((ImageView)this.findViewById(R.id.backButton)).setOnClickListener(goBack); 
} 


private final OnClickListener goBack = new OnClickListener() { 
    @Override 
    public void onClick(View v) { 
    mActivity.finish(); 
    } 
}; 

我希望這會有所幫助!

+0

試過這個,但是當膨脹類到inster到佈局時,我得到下面的'下面的類不能實例化',它引用我定義活動的行 – masmic