【问题标题】:Removing Fragment by clicking/touching outside:通过单击/触摸外部来删除片段:
【发布时间】:2013-03-10 14:41:29
【问题描述】:

我有一些片段是使用代码从RelativeLayout 动态添加和删除的。其中一个片段是ListFragment,与其他具有关闭和保存按钮的片段相反,这个片段仅包含一个列表。

我的目标是通过在 Activity 中的任何位置单击该片段外部来关闭/删除该片段。

我找到了以下代码:

@Override
public boolean onTouchEvent(MotionEvent event) {
    // I only care if the event is an UP action
    if (event.getAction() == MotionEvent.ACTION_UP) {
        // create a rect for storing the window rect
        Rect r = new Rect(0, 0, 0, 0);
        // retrieve the windows rect
        this.getWindow().getDecorView().getHitRect(r);
        // check if the event position is inside the window rect
        boolean intersects = r.contains((int) event.getX(), (int) event.getY());
        // if the event is not inside then we can close the activity
        if (!intersects) {
            // close the activity
            this.finish();
            // notify that we consumed this event
            return true;
        }
    }
    // let the system handle the event
    return super.onTouchEvent(event);
}

点击外部时关闭非全屏活动,但我似乎不明白如何找到我的片段矩形。

有人能帮我指出正确的方向吗?任何帮助将不胜感激。

谢谢。

【问题讨论】:

    标签: android android-fragments touch-event


    【解决方案1】:

    好吧,我终于想通了:

    @Override
    public boolean onTouchEvent ( MotionEvent event ) 
    {
        // I only care if the event is an UP action
        if ( event.getAction () == MotionEvent.ACTION_UP ) 
        {
            //and only is the ListFragment shown.
            if (isListFragmentShown)
            {   
                // create a rect for storing the fragment window rect
                Rect r = new Rect ( 0, 0, 0, 0 );
                // retrieve the fragment's windows rect
                currentFragment.getView().getHitRect(r);
                // check if the event position is inside the window rect
                boolean intersects = r.contains ( (int) event.getX (), (int) event.getY () );
                // if the event is not inside then we can close the fragment
                if ( !intersects ) {
                    Log.d(TAG, "pressed outside the listFragment");
                    FragmentTransaction fragmentTransaction;
                    fragmentTransaction = fragmentManager.beginTransaction();
                    fragmentTransaction.remove(currentFragment).commit();
                    // notify that we consumed this event
                    return true;
                }
            }
        }
        //let the system handle the event
        return super.onTouchEvent ( event );
    }
    

    【讨论】:

      【解决方案2】:

      您可以将点击监听器添加到您的容器RelativeLayout。如果片段已启动,则激活您的 RelativeLayout 的侦听器,以便侦听器仅在片段存在时起作用。

      【讨论】:

      • 没看懂你的回答,你把我的问题看完了吗?
      猜你喜欢
      • 1970-01-01
      • 2019-01-14
      • 1970-01-01
      • 1970-01-01
      • 2012-11-22
      • 1970-01-01
      • 2023-03-15
      • 2016-11-20
      • 1970-01-01
      相关资源
      最近更新 更多