我正在尝试制作一个应用程序,用户可以滑动并更改他们在屏幕上看到的片段。我不能使用视图分页器,因为我希望用户能够永远滑动到不同的片段。这是我的片段中的检测器:
class MyGestureDetector extends SimpleOnGestureListener {
@Override
public boolean onDown(MotionEvent e) {
return true;
}
@Override
public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) {
if(e1.getX() - e2.getX() > SWIPE_MIN_DISTANCE & Math.abs(velocityX) > 10) {
left();
} else if (e2.getX() - e1.getX() > SWIPE_MIN_DISTANCE & Math.abs(velocityX) > 10) {
right();
}
return false;
}
@Override
public boolean onScroll(MotionEvent e1, MotionEvent e2, float distanceX, float distanceY){
if(e1.getX() - e2.getX() > SWIPE_MIN_DISTANCE & distanceX > distanceY) {
left();
} else if (e2.getX() - e1.getX() > SWIPE_MIN_DISTANCE & distanceX > distanceY) {
right();
}
return false;
}
}
public void right(){
mCallback.dateNumber(true);
sportView.setText("Loading");
}public void left(){
mCallback.dateNumber(false);
sportView.setText("Loading");
}
在我的Activity中,以下是我添加的用于更改片段的侦听器:
@Override
public void dateNumber(Boolean left_right) {
//true == right
//false == left
if(left_right == false){
day = day + 1;
Fragment1 rightFragment = new Fragment1();
Bundle args = new Bundle();
args.putInt("day", day);
rightFragment.setArguments(args);
android.support.v4.app.FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
transaction.replace(R.id.fragment_container, rightFragment);
transaction.addToBackStack(null);
transaction.commit();
}else if(left_right == true){
day = day - 1;
Fragment1 leftFragment = new Fragment1();
Bundle args = new Bundle();
args.putInt("day", day);
leftFragment.setArguments(args);
android.support.v4.app.FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
transaction.replace(R.id.fragment_container, leftFragment);
transaction.addToBackStack(null);
transaction.commit();
}
left_right = null;
}
我知道滑动手势总是被识别,但有时新的片段不会打开。有人知道为什么吗?
2条答案
按热度按时间06odsfpq1#
首先,你可以使用我的droidQuery库来简化你的刷卡代码:
你可以找到更多关于Fragment transactions here的信息。
另外,考虑保留一个
int offset
变量来跟踪+/-
相对于零的偏移量,例如,你可以从ArrayList
中获取已经示例化的Fragments,然后交换出mArrayList.get(offset)
处的Fragments,当向右划动时,执行offset++
,向左划动时,执行“offset--”。编辑
如注解中所要求的,此代码可用于处理滑动和子图像单击:
将
SwipeInterceptorView
包含在主布局中(res/layout/main.xml
):你需要有类变量:
接下来,在
onCreate
中包含以下组件:当包含ImageView的新Fragment被转换进来时,你需要引用它并更新swipe拦截器的onTouch方法:
iswrvxsc2#
使用Android Support Library v4中的ViewPager和FragmentPagerAdapter。