How to properly terminate an activity from a custom view class?

混江龙づ霸主 提交于 2021-01-29 12:27:13

问题


Similar to this post. Have a custom view (extends EditText) which must have the ability to call the finish() method of the parent activity if the user presses the END key.

How can I access the activity object of the host activity in order to call its finish() method from within the custom view class?

public class SuppressInputEditText extends androidx.appcompat.widget.AppCompatEditText {

    public SuppressInputEditText(Context context) {
        super(context);
    }

    public SuppressInputEditText(Context context, AttributeSet attrs) {
        super(context, attrs);
    }

    public SuppressInputEditText(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
    }
    
    @Override
    public boolean onKeyPreIme(int keyCode, KeyEvent event) {
        return true;
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        return true;
    }

    @Override
    public boolean onKeyUp(int keyCode, KeyEvent event) {
        switch (keyCode){
            case 6: //end key
                //todo: call finish() method of parent activity.
                break;
        }
        return true;
    }
    
}

I can use the getContext() method of my class, available because it inherits from view, to get a context, but I don't know how to use that to access the finish() method. Any help or pointers would be greatly appreciated.

UPDATE: Looking for a solution that can keep the class independent. Thanks!


回答1:


if you know the host i.e the activity where it's custom view is showing then you can do something like this.

(getContext() as? MainActivity)?.finish()

java

((MainActivity)getContext()).finish()

place this under try and catch

Edit: Create an interface which your Host activity implements and pass this as a listener yo your custom view then whenever needed to call this.

for ex.

interface CustomInputEditListener{
  public void onFinish();
}

in your Host activity implement this.

MainActivity extends AppCompatActivity() implements CustomInputEditListener{

 //call this from onCreate()
  public void setHostListener(){
     suppressInputEditText.setHostEditListener(this);
  }

  @Override public void onFinish(){
      finish() ;
  }
}

in your SuppressInputEditText class create a method like this.

public void setHostEditListener(CustomInputEditListener listener){
  this.hostListener = listener;
}

and whenever you need to call finish just call

hostListener.onFinish();



回答2:


Cast context to Activity then call finish like below

Kotlin

(context as? Activity)?.finish()

Java

((Activity) context).finish()


来源:https://stackoverflow.com/questions/63381756/how-to-properly-terminate-an-activity-from-a-custom-view-class

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!