Search code examples
androidbuttonback

Set button function as back key


I'm creating a menu that I want to be in all of my activities. For this, I'm creating a class with all buttons definitions and onClickListeners.

The problem that I encountered is when defining the back button to act as the physical back button. The way I created this class, it doesn't recognize the finish(), onBackPressed() etc.. functions. So, what will be the way to do it this way??

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
    }
};

Solution

  • Declare a context is a member variable and assign it in your constructor like this:

    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);
      }
    

    and in your click listener you can add this line of code:

    ((Activity) context).finish();
    

    Try it. Hope this will work.