About sliding conflicts
In Android development, if it's a simple layout, it's easy to fix, but when it comes to complex pages, especially if you use ScrollView to be compatible with small-screen handsets, there's a lot of click-Event Conflicts, The most classic is the ScrollView nested in the ListView. I think most of the students who have just started to touch Android have stepped into the pit, following the small knitting to see the solution.
Sliding conflict in the same direction
such as ScrollView nesting listview, or scrollview nesting themselves
Let's look at an effect picture
The image above is in the shopping software common pull view picture details, regarding this animation effect realization, actually realizes the overall effect, the method has many, the network has many related examples, but to some details processing is not very clear, for example, The part that is displayed after the drop (for example, the bottom text detail) is also a class ScrollView control (such as WebView), which can create new problems. Here is a look at the following drawing details for the background to do the same direction sliding conflict analysis.
Overall thinking
Here, look at the picture.
Multiple ScrollView nesting diagram
First, make some settings about this picture:
1. The black frame represents the mobile phone screen
2. The green box represents an outer ScrollView
3. The two red boxes represent the two class ScrollView controls that are nested inside, and here we briefly refer to the Sup,sdown
OK, so let's analyze the process of implementing the entire process.
It must be made clear that whenever the visible parts of sup and Sdown are always the height of the phone screen. Knowing this, we can start by following these steps
First, we make sure that the external ScrollView does not intercept the sliding event, so that the SUP must get the event, and then according to its Action_move event, the sup slides to the bottom when it slides downward and its own sliding distance + screen height = its height . , the external scrollview can intercept the sliding event, thus ensuring that the entire view can continue to slide, at which point the bottom sdown is displayed.
Similarly, this time does not allow the external scrollview intercept sliding events, by Sdown processing, according to its Action_move event, when it is up sliding, and its own sliding distance of 0 o'clock, it shows that Sdown has slipped to the top , At this point the external scrollview can also get the right to intercept sliding events, so as to ensure that the entire view can continue to slide up, at this time the SUP again show, and start a new round of circular interception.
Such a whole process can realize the effect of moving diagram. OK, finish the principle, or look at the code.
Code implementation
SUP implementation
public class Upscrollview extends ScrollView {/** * screen height * * private int mscreenheight;
/** * Last coordinate * * private float mlasty;
/** * Current View sliding distance * * private int mscrolly;
/** * Current view of the control height * * private int MCHILDH;
Public Upscrollview {Super (context);
Init (context);
Public Upscrollview (context, AttributeSet attrs) {Super (context, attrs);
Init (context);
Public Upscrollview (context, AttributeSet attrs, int defstyleattr) {Super (context, attrs, defstyleattr);
Init (context); } private void Init (context context) {WindowManager wm = (WindowManager) context.getsystemservice (Context.window_servi
CE);
Displaymetrics dm = new Displaymetrics ();
Wm.getdefaultdisplay (). Getmetrics (DM);
Mscreenheight = Dm.heightpixels; @Override public boolean ontouchevent (motionevent ev) {//default top-level view does not intercept GetParent (). GetParent (). Requestdisallowint
Ercepttouchevent (TRUE); Switch (ev.getaction ()) {case MotionEvent.ACTION_DOWN:mLasty = (int) ev.gety ();
Break
Case MotionEvent.ACTION_MOVE:float y = ev.gety ();
float DeltaY = y-mlasty;
MCHILDH = This.getchildat (0). Getmeasuredheight ();
int translatey = mchildh-mscrolly; Sliding up, if translatey equals screen height, that means sliding to the bottom, and top view control sliding if (DeltaY < 0 && Translatey = = mscreenheight) {Getpare
NT (). GetParent (). Requestdisallowintercepttouchevent (false);
} break;
Default:break;
return super.ontouchevent (EV); @Override protected void onscrollchanged (int l, int t, int oldl, int Oldt) {super.onscrollchanged (L, T, OLDL, Oldt)
;
mscrolly = t; }
}
Here in the action_move to do subtraction, in fact, the same reason.
Onscrollchanged is implemented in the view class, viewing its API to see its second parameter T interpretation
@param t Current vertical scroll origin.
This is the current view of the sliding distance
Sdown implementation
public class Mywebview extends WebView {public float oldy;
private int t;
Public Mywebview {Super (context);
Init ();
Public Mywebview (context, AttributeSet attrs) {Super (context, attrs);
Init ();
Public Mywebview (context, AttributeSet attrs, int defstyleattr) {Super (context, attrs, defstyleattr);
Init ();
private void Init () {websettings settings = GetSettings ();
Settings.setjavascriptenabled (TRUE);
Setwebviewclient (New Webviewclient () {@Override public boolean shouldoverrideurlloading (webview view, String URL) {
View.loadurl (URL);
return true;
}
}); @Override public boolean ontouchevent (motionevent ev) {getparent (). GetParent (). Requestdisallowintercepttouchevent (
true);
Switch (ev.getaction ()) {Case MotionEvent.ACTION_DOWN:oldY = ev.gety ();
Break
Case MotionEvent.ACTION_MOVE:float Y = Ev.gety ();
float Ys = Y-oldy; if (Ys > 0 && t = = 0) {getparent (). GetParent (). RequestDisallowintercepttouchevent (FALSE);
} break;
return super.ontouchevent (EV);
@Override protected void onscrollchanged (int l, int t, int oldl, int oldt) {this.t = t;
Super.onscrollchanged (L, T, OLDL, Oldt); }
}
See above, here at the bottom of the view did not inherit ScrollView, but chose to inherit the WebView, here just for convenience, of course, inheritance ScrollView is no problem. This just needs to be considered as it is, because the content of the bottom graphic details is a webview loading data.
The implementation of this class should be well understood in terms of the principles previously stated.
External ScrollView
public class Customerscrollviews extends ScrollView {/** * screen height * * private int mscreenheight;
Private Upscrollview Upscrollview;
Private Mywebview Mywebview;
Private Boolean init = false;
private float Fator = 0.2f;
private int factorheight;
Private Boolean upshow = true;
Public Customerscrollviews {Super (context);
Init (context);
Public Customerscrollviews (context, AttributeSet attrs) {Super (context, attrs);
Init (context); Customerscrollviews (context, AttributeSet attrs, int defstyleattr) {Super (context, Attrs, Defstyleatt
R);
Init (context); } private void Init (context context) {WindowManager wm = (WindowManager) context.getsystemservice (Context.window_servi
CE);
Displaymetrics dm = new Displaymetrics ();
Wm.getdefaultdisplay (). Getmetrics (DM);
Mscreenheight = Dm.heightpixels;
Factorheight = (int) (mscreenheight * Fator); @Override protected void onmeasure (int widthmeasurespec, int heightmeasurespec{if (!init) {linearlayout Parentview = (linearlayout) getchildat (0);
Obtain the interior of the two view Upscrollview = (upscrollview) parentview.getchildat (0);
Mywebview = (Mywebview) parentview.getchildat (2);
and set its height to screen height upscrollview.getlayoutparams (). height = mscreenheight;
Mywebview.getlayoutparams (). height = mscreenheight;
init = true;
} super.onmeasure (Widthmeasurespec, Heightmeasurespec); @Override protected void OnLayout (Boolean changed, int l, int t, int r, int b) {super.onlayout (changed, L, T, R, B)
;
if (changed) {scrollto (0, 0);
@Override public boolean ontouchevent (motionevent ev) {switch (ev.getaction ()) {case MOTIONEVENT.ACTION_UP:
int scrolly = getscrolly ();
if (upshow) {if (scrolly <= factorheight) {smoothscrollto (0, 0);
else {smoothscrollto (0, mscreenheight);
Upshow = false;
} else {int scrollpadding = mscreenheight-scrolly; if (scrollpadding >= factorheight) {this.smoothscrollto (0, 0);
Upshow = true;
else {this.smoothscrollto (0, mscreenheight);
} return true;
return super.ontouchevent (EV); }
}
The implementation of this class is very flexible, in the Onmeasure method in the initialization of the internal view, in the Ontouch method can be based on the actual requirements of the implementation of different logic, here just to imitate the effect of viewing the text details, The logic is simple to shift the entire view through the ScrollView Smoothscrollto method.
Here is a place to focus:
Upscrollview = (upscrollview) parentview.getchildat (0);
Mywebview = (Mywebview) parentview.getchildat (2);
You might wonder where the middle child (1) went. And here's the mainactivity layout file.
Dual_scrollview_activity_layout1.xml
<?xml version= "1.0" encoding= "Utf-8"?> <linearlayout xmlns:android= "http://schemas.android.com/apk/res/" Android "Android:layout_width=" Match_parent "android:layout_height=" match_parent "android:orientation=" vertical "
> <com.example.dreamwork.activity.superscrollview.customerscrollviews android:layout_width= "match_parent" android:layout_height= "Match_parent" > <linearlayout android:layout_width= "match_parent" Android:layout_ height= "wrap_content" android:orientation= "vertical" > < Com.example.dreamwork.activity.superscrollview.UpScrollView android:layout_width= "Match_parent" Android:layout_ height= "wrap_content" android:scrollbars= "vertical" > <linearlayout android:layout_width= "match_parent" an droid:layout_height= "wrap_content" android:orientation= "vertical" > <imageview android:layout_width= "Match_" Parent "android:layout_height=" wrap_content "android:scaletype=" Fitxy "android:src=" @drawable/taobao "/>
<imageview android:layout_width= "match_parent" android:layout_height= "wrap_content" android:scaleType= "FitXY" android:src= "@drawable/taobao"/> <textview android:textsize= "20sp" android:padding= "10DP" android:g ravity= "center" android:layout_margintop= "20DP" android:layout_marginbottom= "60DP" android:text= "View graphic Details" Andro Id:layout_width= "Match_parent" android:layout_height= "wrap_content"/> </LinearLayout> </com.example.d reamwork.activity.superscrollview.upscrollview> <include layout= "@layout/selector_tab_items"/> < Com.example.dreamwork.activity.superscrollview.MyWebView android:id= "@+id/web" android:layout_width= "Match_ Parent "android:layout_height=" match_parent "/> </LinearLayout> </ Com.example.dreamwork.activity.superscrollview.customerscrollviews> </LinearLayout>
The entire layout file shows that we placed two custom scrollview inside the outermost custom scrollview of customerscrollviews (as we saw in the schematic). Only in the middle of these two ScrollView controls is placed a linearlayout through the layout, the contents of which are seen in the moving map of the middle of the word qq,baidu to switch webview content of a view. There's no code here.
In this way, you can understand why the previous child (1) has been skipped.
Use
public class DualScrollViewActivity1 extends activity implements View.onclicklistener {private Mywebview webview;
Private TextView Sinatv, QQTV, BAIDUTV;
Private View line1, line2, Line3;
Private final String BAIDU = "http://www.baidu.com";
Private final String QQ = "http://www.qq.com";
Private final String SINA = "http://sina.cn";
@Override protected void OnCreate (Bundle savedinstancestate) {super.oncreate (savedinstancestate);
Requestwindowfeature (Window.feature_no_title);
Initview ();
Sinatv.performclick ();
private void Initview () {Setcontentview (R.LAYOUT.DUAL_SCROLLVIEW_ACTIVITY_LAYOUT1);
WebView = V.F (this, r.id.web);
SINATV = V.F (this, r.id.one);
Sinatv.setonclicklistener (this);
QQTV = V.F (this, r.id.two);
Qqtv.setonclicklistener (this);
BAIDUTV = V.F (this, r.id.three);
Baidutv.setonclicklistener (this);
Line1 = V.F (this, r.id.line1);
Line2 = V.F (this, r.id.line2);
Line3 = V.F (this, r.id.line3); @Override public void OnClick (View v) {ReseT ();
String url = "";
Switch (V.getid ()) {case r.id.one:line1.setvisibility (view.visible);
url = SINA;
Break
Case R.id.two:line2.setvisibility (view.visible);
url = QQ;
Break
Case R.id.three:line3.setvisibility (view.visible);
url = BAIDU;
Break
Default:break;
} webview.loadurl (URL);
private void Reset () {line1.setvisibility (view.gone);
Line2.setvisibility (View.gone);
Line3.setvisibility (View.gone); }
}
About the bottom view content update, WebView by loading different URLs to achieve different view effects, just as a demo test, the actual should consider through the fragment switch implementation.
Here the solution to the sliding conflict, is from the inside out, the default so that the top view lost interception ability, in the bottom view of the sliding distance, make different logical judgments control the top of the interception or not; This is also relatively easy to understand and realize the idea. There are, of course, many different ways of thinking about this kind of sliding conflict, and here is just one list.
In the actual development, this kind of control with the same direction sliding characteristics nested, the problem is not only sliding conflict, sometimes the content will not display or display.
The most common, such as ScrollView nesting ListView, is only a custom ListView to make its height to a very large value, in a sense let it lose the characteristics of sliding, but this also makes ListView seemingly lost view recycling mechanism, This time, if loading a lot of many pictures, the effect will be very unsatisfactory. In this case, adding Headview and Footview to ListView is also a solution, but the actual UI condition is also allowed.
ScrollView nesting Recyclerview is a bit of a hassle, you need to customize ScrollView, and you need to customize the implementation Linearlayoutmanager.
Sliding conflict in different directions
such as ScrollView nesting viewpager, or viewpager nesting scrollview, this situation is very typical. Now most of the application outermost is the viewpager+fragment of the bottom of the switch (such as micro-letter) structure, this time, it is easy to slip conflict. But Viewpager inside whether is nested ListView or ScrollView, sliding conflict is not, after all, is the official thing, may have taken into account these, so relatively perfect.
The complicated sliding conflict is basically the result of the combination of these two conflicts.
The idea of sliding conflict resolution
Sliding conflict, by its very nature, has two different directions (or the same direction) view, one of them is the dominant, always grab to deal with the outside of the sliding behavior, which leads to a very awkward user experience, obviously just sideways slide, vertical list but in the vertical direction of the action. So, this dominant view, each time involuntarily intercepted this sliding action, therefore, to solve the sliding conflict, is to clearly tell the dominant view, when you should intercept, when you should not intercept, should be the next layer of view to deal with this sliding action.
This does not understand the classmate, you can go to understand the Android touch event distribution mechanism, which is the core knowledge to resolve the sliding conflict.
Sliding conflict
Here, let's talk about the background. Before doing a drop-down refresh, pull load more always use the Pulltorefreshview this control, because it is very convenient, do not import the three-party project. In its interior can be placed Listview,gridview and ScrollView, very convenient, use it is a proven. But until one day, as a result of the project needs, at the top of the ListView add a Carousel Map control Bannerview (this can refer to a previous study note written). The results show that the rotation of the carousel graph is in conflict with the vertical drop-refresh component.
As mentioned before, the key to solving sliding conflicts is to explicitly tell the view that received the touch, whether or not to intercept the event.
Solving method
Solution 1, consider from an external interception mechanism
Here, the equivalent is Pulltorefreshview nested viewpager, then each priority received touch event is necessarily pulltorefreshview. So it's clear, look at the code:
In the Pulltorefreshview:
@Override Public
Boolean onintercepttouchevent (Motionevent e) {
int y = (int) e.getrawy ();
int x = (int) e.getrawx ();
Boolean resume = false;
Switch (e.getaction ()) {case
Motionevent.action_down:
//When a Down event occurs, the record y coordinate
mlastmotiony = y;
Mlastmotionx = x;
Resume = false;
break;
Case Motionevent.action_move:
//deltay > 0 is down motion,< 0 is up motion
int deltay = y-mlastmotiony;
int deleax = X-mlastmotionx;
if (Math.Abs (DELEAX) > Math.Abs (DeltaY)) {
resume = false;
} else {
//is currently in slide
if ( Isrefreshviewscroll (DeltaY)) {
resume = true;
}
}
break;
Case MOTIONEVENT.ACTION_UP: Case
motionevent.action_cancel: Break
;
}
return resume;
}
The most critical code here is this line.
if (Math.Abs (DELEAX) > Math.Abs (DeltaY)) {
resume = false;
}
When the transverse sliding distance is greater than the longitudinal, there is no need to intercept this sliding event. In fact, it is that simple, but only if you have a clear understanding of the Android touch event delivery mechanism, the sequence and meaning of each method.
Solution 2, from the content of reverse thinking analysis
Sometimes, we do not want to modify the introduced Third-party controls, or to say that they cannot be modified. You have to consider the reverse of the view from the current one in the touch delivery event. First of all, from the Android view of the touch event delivery mechanism, we know that touch events, first of all, must be intercepted by the outermost view, if you can not change the outermost view, then is not the case? In fact, Android is so big on the system must take into account this problem, good nonsense do not say, first look at the code
Private Bannerview Carouselview;
Private context Mcontext;
Private Pulltorefreshview Refreshview; ... refreshview.setontouchlistener (new View.ontouchlistener () {@Override public boolean ontouch (View V, motio
Nevent event) {carouselview.getparent (). Requestdisallowintercepttouchevent (false);
return false;
}
}); Carouselview.setontouchlistener (New View.ontouchlistener () {@Override public boolean ontouch (View V, motionevent even
T) {carouselview.getparent (). Requestdisallowintercepttouchevent (True);
int x = (int) event.getrawx ();
int y = (int) Event.getrawy ();
Switch (event.getaction ()) {Case MotionEvent.ACTION_DOWN:lastX = x;
Lasty = y;
Break
Case MotionEvent.ACTION_MOVE:int DeltaY = y-lasty;
int deltax = X-LASTX;
if (Math.Abs (DeltaX) < Math.Abs (DeltaY)) {carouselview.getparent (). Requestdisallowintercepttouchevent (false);
else {carouselview.getparent (). Requestdisallowintercepttouchevent (True); }
Default:break;
return false; }
});
Let's start with this method.
public abstract void Requestdisallowintercepttouchevent (Boolean disallowintercept)
The meaning in the API is clear, and the child view can call this method if it does not want its parent view to intercept the touch event. When disallowintercept this argument is true, the parent view will not intercept.
PS: This method of naming and its parameters of the use of logic, let me think of a very interesting words, enemies of the enemy is a friend, I really do not know how the great god of Google Think, do not have to engage in a reverse logic.
Anyway Here the interception is straightforward and clear, and in the Carouselview Ontouch method, the parent view is set to not intercept the event, and then at motion_move time, Depending on the distance of the slide, the decision is whether the parent view has the right to intercept the touch event (i.e. sliding behavior).
Summarize
Well, this article to the basic end, this article is only a solution to provide a way of thinking, in a specific scenario, the interaction is often a specific business needs. However, it is most important to find out the timing of the Click event truncation and processing, and the solution is always found around this key point.