sliding one fragment over another in Android

2019-03-09 18:54发布

问题:

In android, can we slide a fragment over another? For example, in the following image :

There are two fragments. One is red colored, and the other blue colored. If the user presses his finger on the black colored arrow and drags it to the right, the red colored fragment also drags along with it, thereby covering the blue fragment. In the end, the red fragment covers the whole blue fragment. Also, if the user lifts his finger before the red fragment has been dragged onto less than half of the blue fragment, the red fragment should come back to its original place (and thus not cover the blue fragment). However if the user does not lift his finger (i.e. drags the arrow) till the red fragment covers more than half of the blue fragment, or the whole blue fragment, then the red fragment should cover the whole blue fragment.

Also, if there are any views on the red colored fragment (like, Buttons, EditTexts etc.), then they will also get re-sized accordingly.

Is there any way to do this? If yes, then how?

回答1:

Have you looked at using or extending SlidingDrawer? You could have the red fragment as the content of the drawer and the black arrow as the handle.



回答2:

I guess what you are trying to do is something like the latest Android Market UI? Where you can slide through fragments showing different stuff, right?

If that's it then I recommend you to take a look at this site: http://viewpagerindicator.com/

It is a project done by Jake Wharton which does what you are asking for. You can download its source code to find a way of implementing it yourself or you can simply use it as a library (it is as well explained in the website).

For additional information I would recommend you taking a look to Fragments and FragmentActivity in Android, here goes a link to an example that uses both Fragments and FragmentActivity but there are plenty on the internet: http://www.e-nature.ch/tech/?p=6

Hope this helps!



回答3:

I suppose you would use a custom viewgroup that extends a linearlayout. The internal views should have layout weight to define their part of the screen.

You must override you custom viewgroups onLayout and onMeassure, remember that a viewgroup calls for meassurements and layouts of its children, for smooth rescaling.

Hope it helps.



回答4:

I can't think of easier way...so try to do it like this:

Try using FrameLayout. Add one blue LinearLayout, after that add one red LinearLayout, for example. Then red layout would be uppon blue one.

Attach onTouch listener on red layout. Do some simple calculation of x and y coordinates, that TouchEvent gives you, to programmaticaly set LayoutParams of red layout, width for instance.

That's idea from top of my head, never had tried it.

Hope that helps you. Cheers!