大家好,我的应用程序中有一个活动,可以添加许多片段。片段由包含96x96缩略图的单个图像视图组成,并以网格布局放置。我想要的是在检测到onFling手势时删除特定片段。

这是我尝试的。我有

public class BlankFragment extends Fragment
{
    ImageView image;
    GestureDetector mDetector;
    GestureDetector.OnGestureListener gestureListener;
    public BlankFragment() {
        // Required empty public constructor
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState)
    {
        cr = getActivity().getContentResolver();
        mDetector = new GestureDetector(getActivity().getApplicationContext(),new MyFlingGesture());
        image = new ImageView(getActivity().getApplicationContext());

        image.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View view, MotionEvent motionEvent) {
                mDetector.onTouchEvent(motionEvent);
                return true;
            }
        });


        return image;
    }
    class MyFlingGesture extends GestureDetector.SimpleOnGestureListener {
        @Override
        public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) {
            FragmentManager fragmentManager = getFragmentManager();
            FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
            fragmentTransaction.remove(// what to pass here);
            // or what is the other ways?
            return super.onFling(e1, e2, velocityX, velocityY);
        }
    }

}


如果我在手机上进行测试,则可以检测到Fling手势。如何删除该片段?

最佳答案

如果您将片段放在后台,只需调用finish()即可。如果您不将碎片放在后堆栈上,或者只想确保它可以工作,请使用:

首先,您需要添加field来存储活动片段。在您的BlankFragment类中添加

public BlankFragment mBlankFragment;


oncreateview中添加

mBlankFragment = this;


现在,您可以使用以下方式在fling监听器中使用此变量:

 getActivity().getFragmentManager().beginTransaction().remove(mBlankFragment).commit();




另一种方法是使用诸如

public Fragment getVisibleFragment(){
    FragmentManager fragmentManager = getActivity().getFragmentManager();
    List<Fragment> fragments = fragmentManager.getFragments();
    for(Fragment fragment : fragments){
        if(fragment != null && fragment.isVisible())
            return fragment;
    }
    return null;
}

10-08 03:08