我有一些使用代码动态添加和删除RelativeLayout
的片段。其中一个片段是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);
}
在点击它之外时关闭了一个非全屏活动,但我似乎不明白如何找到我的片段矩形。
有人可以协助并指出我正确的方向吗?任何帮助将不胜感激。
感谢。
答案 0 :(得分:6)
好吧,我终于弄明白了:
@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 :(得分:1)
您可以将click侦听器添加到容器RelativeLayout。如果片段是关于动作的,那么激活你的RelativeLayout的监听器,这样只有片段存在时监听器才有效。