操作栏是隐藏的,在那之后立刻所示在那、所示、操作

2023-09-12 03:14:49 作者:挽歌扰残风

我试图切换显示/隐藏操作栏上活动的用户点击,让我实现了这个功能,像这样的活动:

I'm trying to toggle show/hide action bar on user click on activity, so I've implemented this functionality like this in activity:

@Override
public boolean dispatchTouchEvent(MotionEvent ev) {
    Log.d("ACTION BAR", "triggered");

    super.dispatchTouchEvent(ev);

    ActionBar actionBar = getSupportActionBar();
    actionBar.hide();

    if (actionBar.isShowing()) {
        actionBar.hide();
    } else {
        actionBar.show();
    }

    return true;
}

然而,问题是,在活动单击时,操作栏被隐藏,但随即再次显示。我已经添加了记录,似乎这种方法被触发了两次,为什么这样呢?

However, the problem is that when clicked on activity, the action bar gets hidden but then immediately is shown again. I've added logging and it seems that this method is triggered twice, why so?

推荐答案

我觉得dispatchTouchEvent可能被称为两次触摸下,上行动,以便需要一个布尔标志和显示操作栏前检查此标志值:

I think dispatchTouchEvent might be called two time on touch down and up action so take one boolean flag and check this flag value before showing action bar :

private boolean isManuallyHideShownActionBar;

@Override
public boolean dispatchTouchEvent(MotionEvent ev) {
    super.dispatchTouchEvent(ev);

    ActionBar actionBar = getSupportActionBar();

    if(!isManuallyHideShownActionBar){
        if (actionBar.isShowing()) {
            actionBar.hide();
        } else {
            actionBar.show();
        }
        isManuallyHideShownActionBar = true;
    }else{
        isManuallyHideShownActionBar = false;
    }

    return true;
}