2013-03-10 40 views
5

Tôi có một số đoạn được thêm vào và xóa khỏi mã sử dụng động RelativeLayout. một trong các Fragments là ListFragment và ngược lại với các đoạn khác của tôi có nút Đóng và Lưu, phần này chỉ chứa một danh sách.Xóa Phân đoạn bằng cách nhấp/chạm vào bên ngoài:

Mục tiêu của tôi là đóng/xóa đoạn này bằng cách nhấp vào bên ngoài phân đoạn đó ở bất kỳ vị trí nào trong hoạt động.

Tôi đã tìm thấy đoạn mã sau:

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

Đó đóng một hoạt động không toàn màn hình khi nhấp bên ngoài của nó, nhưng tôi dường như không hiểu làm cách nào để tìm hình chữ nhật mảnh của tôi.

Có thể một số hỗ trợ và chỉ cho tôi đúng hướng không? Bất kỳ trợ giúp sẽ được đánh giá cao.

Cảm ơn.

Trả lời

5

Vâng, tôi cuối cùng đã tìm ra này:

@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

Bạn có thể thêm trình nghe nhấp chuột vào vùng chứa của mình RelativeLayout. Nếu phân mảnh là về hành động thì kích hoạt trình lắng nghe của RelativeLayout để người nghe chỉ hoạt động trong khi đoạn tồn tại.

+0

đã không thực sự hiểu câu trả lời của bạn, bạn đã đọc câu hỏi của tôi cho đến cuối cùng? –

Các vấn đề liên quan