Krishnabhadra
Krishnabhadra

Reputation: 34285

Android floating view across activities

Requirement

I have an application with 2 activities, say A and B, with navigations like A->B and B->A (on back press). My requirement is

What I found out

I did some searching, and from what I could find, there are 2 methods to reuse layout in android

Another hint of my requirement

For people familiar with iPhone development you can add view's to UIWindow, which stays there irrespective of which UIViewController is currently active. I want exact behavior in my application.

My original setup

I am targeting android 2.1 and above. It seems Fragment is available from API level 11 (android 3.0) and above. One option is to use android compatibility library that enables usage of Fragment in older versions. I am currently researching on that now. But I also would like to know if there is any other methods available to fulfill my requirement, rather than change my entire project and use fragments.

I have around 30 odd activities in my application and I want this layout floating over all of them. I just made out a test case with 2 activities to make the question simple and easy.

Upvotes: 6

Views: 6339

Answers (1)

Jonathan Schneider
Jonathan Schneider

Reputation: 27727

Solution 1: FrameLayout

I think what you want to use is the FrameLayout. FrameLayout is designed to block out an area on the screen to display a single item. Child views are drawn in a stack, with the most recently added child on top.

http://developer.android.com/reference/android/widget/FrameLayout.html

Then read here about the back stack that you could use in your activity to flip back and forth between the activities using the back button:

http://developer.android.com/guide/topics/fundamentals/tasks-and-back-stack.html

Solution 2: Fragment Transactions

Rather than code two separate Activities, code a single Activity with two Fragments. Here is a blurb from the Fragments documentation:

"A fragment must always be embedded in an activity and the fragment's lifecycle is directly affected by the host activity's lifecycle. For example, when the activity is paused, so are all fragments in it, and when the activity is destroyed, so are all fragments. However, while an activity is running (it is in the resumed lifecycle state), you can manipulate each fragment independently, such as add or remove them. When you perform such a fragment transaction, you can also add it to a back stack that's managed by the activity—each back stack entry in the activity is a record of the fragment transaction that occurred. The back stack allows the user to reverse a fragment transaction (navigate backwards), by pressing the Back button."

Upvotes: 2

Related Questions