7

RelativeLayout動的に使用するコードに追加および削除されるフラグメントがいくつかあります。フラグメントの 1 つは で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 に答える