2013-03-10 7 views
5

मेरे पास कुछ टुकड़े हैं जिन्हें RelativeLayout से गतिशील रूप से कोड का उपयोग करके जोड़ा और हटा दिया गया है। फ्रैगमेंट्स में से एक ListFragment है, और मेरे अन्य टुकड़ों का विरोध करने के रूप में जिनके पास बंद और सहेजें बटन हैं, इनमें से केवल एक सूची है।बाहर क्लिक करके/स्पर्श करके Fragment को हटा रहा है:

मेरा लक्ष्य गतिविधि में किसी भी स्थान पर इसके बाहर क्लिक करके इस खंड को बंद/निकालना है।

मैं निम्नलिखित कोड मिल गया है:

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

यह एक नहीं पूर्ण स्क्रीन गतिविधि बंद कर देता है जब इसके बारे में बाहर क्लिक, लेकिन मैं सिर्फ समझने के लिए मैं अपने टुकड़ा आयत पाते हैं नहीं है।

क्या कोई मुझे सही दिशा में सहायता और इंगित कर सकता है? किसी भी सहायता की सराहना की जाएगी।

धन्यवाद।

उत्तर

5

खैर मैं अंत में यह पता लगा है:

@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

आप अपने कंटेनर रिलेवेटिवआउट पर क्लिक श्रोता जोड़ सकते हैं। यदि टुकड़ा कार्रवाई के बारे में है तो अपने रिलेवेटिवआउट के श्रोता को सक्रिय करें ताकि श्रोता केवल तभी काम करता है जब खंड मौजूद हो।

+0

वास्तव में अपने जवाब में समझा नहीं था, तो आप अंत तक मेरे सवाल पढ़ा है? –

संबंधित मुद्दे