Emi*_*Adz 6 android touch-event android-fragments
我有一些RelativeLayout
动态使用代码添加和删除的片段.其中一个片段是a ListFragment
,并且与其他具有Close和Save Buttons的片段相反,这个片段只包含一个列表.
我的目标是通过在活动中的任何位置单击它以外来关闭/删除此片段.
我找到了以下代码:
@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);
}
Run Code Online (Sandbox Code Playgroud)
当点击它外面时,这会关闭一个不全屏的活动,但我似乎不明白如何找到我的片段矩形.
有人可以协助并指出我正确的方向吗?任何帮助,将不胜感激.
谢谢.
好吧,我终于弄明白了:
@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 );
}
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
4265 次 |
最近记录: |