2013-03-10 25 views
5

Mam kilka fragmentów, które są dodawane i usuwane z RelativeLayout dynamicznie za pomocą kodu. Jednym z Fragmentów jest ListFragment, a jako przeciwny do innych moich fragmentów, które mają Przyciski Zamknij i Zapisz, ten zawiera tylko listę.Usuwanie fragmentu przez kliknięcie/dotknięcie na zewnątrz:

Moim celem jest zamknięcie/usunięcie tego fragmentu, klikając poza nim w dowolnym miejscu aktywności.

znalazłem następujący kod:

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

który zamyka działalność nie na pełnym ekranie po kliknięciu poza nim, ale ja po prostu nie wydają się zrozumieć, w jaki sposób mogę znaleźć fragment prostokąt.

Czy ktoś może pomóc i wskazać mi właściwy kierunek? Każda pomoc będzie doceniona.

Dzięki.

Odpowiedz

5

Dobrze I w końcu zorientowaliśmy się:

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

Możesz dodać detektor kliknięcia do swojego kontenera RelativeLayout. Jeśli fragment zawiera informacje o akcjach, aktywuj odbiornik RelativeLayout, aby słuchacz działał tylko wtedy, gdy fragment istnieje.

+0

naprawdę nie zrozumiał swoją odpowiedź, że czytasz moje pytanie aż do końca? –

Powiązane problemy