我有抽屉布局,它工作正常。但我想在片段上右键滑动后打开导航抽屉。你能帮我解决这个问题。
这是我的倾听者。
public class OnSwipeTouchListener implements View.OnTouchListener {
private final GestureDetector gestureDetector;
public OnSwipeTouchListener(Context context) {
gestureDetector = new GestureDetector(context, new GestureListener());
}
public void onSwipeLeft() {
}
public void onSwipeRight() {
}
public boolean onTouch(View v, MotionEvent event) {
return gestureDetector.onTouchEvent(event);
}
private final class GestureListener extends GestureDetector.SimpleOnGestureListener {
private static final int SWIPE_DISTANCE_THRESHOLD = 100;
private static final int SWIPE_VELOCITY_THRESHOLD = 100;
@Override
public boolean onDown(MotionEvent e) {
return true;
}
@Override
public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) {
float distanceX = e2.getX() - e1.getX();
float distanceY = e2.getY() - e1.getY();
if (Math.abs(distanceX) > Math.abs(distanceY) && Math.abs(distanceX) > SWIPE_DISTANCE_THRESHOLD && Math.abs(velocityX) > SWIPE_VELOCITY_THRESHOLD) {
if (distanceX > 0)
onSwipeRight();
else
onSwipeLeft();
return true;
}
return false;
}
}
}
片段
中的用法public class ChartsFragment extends Fragment {
public ChartsFragment(){}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_charts, container, false);
rootView.setOnTouchListener(new OnSwipeTouchListener(getActivity().getApplicationContext()){
@Override
public void onSwipeRight() {
Log.v("SWIPE", "SWIPE");
}
});
return rootView;
}
}
但我不知道如何打开抽屉,因为它在另一个类(MainActivity)中
mDrawerLayout.openDrawer(linearLayout);
感谢Pankaj Arora
的解决方案:
final DrawerLayout mDrawerLayout = (DrawerLayout)getActivity().findViewById(R.id.drawer_layout);
rootView.setOnTouchListener(new OnSwipeTouchListener(getActivity().getApplicationContext()){
@Override
public void onSwipeRight() {
mDrawerLayout.openDrawer(Gravity.START);
Log.v("SWIPE", "SWIPE");
}
});
答案 0 :(得分:2)
尝试在您的片段中获取抽屉布局的ID,如。
//全球
DrawerLayout mDrawerLayout
在oncreateview中
mDrawerLayout = getactivity().findviewbyid(R.id.your drawer layout id);
然后在onswipe右边调用
mDrawerLayout.openDrawer(Gravity.Start);