Floating Views in Android (Buttons)
Have you seen other applications with Buttons (or other views, but mainly Buttons) that stay in one spot, even if you're scrolling through a list? These are commonly known as floating Buttons or Views.
This is actually used a lot on websites as well, and they may seem hard to produce at first glance, but it's actual quite easy.
I'll run you through an easy application that uses one floating button within a ListActivity, which is aligned to the bottom right of the screen - on top of the ListView.
Here is what your end product should look like when we're finished:
And here is the main Activity:
public class FloatingViewApp extends ListActivity {
@Override
public void onCreate(Bundle icicle) {
super.onCreate(icicle);
setContentView(R.layout.main);
String[] mStrings = new String[] {"Item 1", "Item 2", "Item 3", "Item 4", "Item 5", "Item 6", "Item 7", "Item 8", "Item 9", "Item 10", "Item 11", "Item 12"};
this.setListAdapter(new ArrayAdapter(this, android.R.layout.simple_list_item_1, mStrings));
}
}
Here we setup our content view and fill an array of strings with items, which is just to demonstrate how the floating works when you scroll through a list.
And lastly we setup the list adapter - not going too much into this, but I'll write another article that explains the use of ListActivity and ArrayAdapter in more detail at a later date.
<?xml version="1.0" encoding="UTF-8"?>
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent">
<LinearLayout android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent">
<ListView android:id="@android:id/list"
android:layout_width="fill_parent"
android:layout_height="fill_parent"/>
<TextView android:id="@android:id/empty"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:text="@string/no_notes"/>
</LinearLayout>
<Button android:id="@+id/floating_button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Floating Button"
android:padding="5dip"
android:layout_margin="5dip"
android:layout_gravity="right|bottom" />
</FrameLayout>
This is the most important bit - this makes the magic happen. I'm using a FrameLayout as the root layout for this one, mainly because it stacks all it's child elements on top of each other, so it makes the floating process easier.
I have 2 child elements in this example - the actual ListView, which is wrapped by a LinearLayout. This is just to make sure that it has items, otherwise it spits out a default message that it has nothing to display.
The second element is the floating button, which is told to display on the bottom right of the screen using layout_gravity.
And voila - there you have your floating view.











Pretty much any View will work the same.
Thanks a million man, now I can trudge on!