7

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

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

我找到了以下代码:

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

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

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

谢谢。

4

2 回答 2

7

好吧,我终于想通了:

@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 );
}
于 2013-03-11T08:35:36.400 回答
2

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

于 2013-03-10T14:53:32.933 回答