I have created a custom title bar as shown in this example
http://staticallytyped.wordpress.com/2011/03/18/android-dynamic-and-custom-title-bars/
"A custom title bar" - half way down.
On some activities I would like to place a button on the right hand side of the titlebar (same as facebook app). I have attempted to add a button to the view as follows, but it doesn't appear.
Custom title bar is displayed as follows
requestWindowFeature(Window.FEATURE_CUSTOM_TITLE);
setContentView(R.layout.maintabhost);
getWindow().setFeatureInt(Window.FEATURE_CUSTOM_TITLE, R.layout.headerbar_include);
Attempting to add button as follows. The button will eventually be an ImageButton and aligned to right of custom titlebar-if I get it working. (just realised I've too many layoutparams now, but this isnt affecting the button display)
LinearLayout layout = (LinearLayout) findViewById(R.id.headerbar);
Button searchButton = new Button(this);
searchButton.setText("info");
LayoutParams layoutParams = new LinearLayout.LayoutParams
(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
searchButton.setLayoutParams(new LayoutParams(
ViewGroup.LayoutParams.WRAP_CONTENT,
ViewGroup.LayoutParams.WRAP_CONTENT));
layout.addView(searchButton, layoutParams);
layout.invalidate();
I could just create another custom titlebar with the button already embedded, but a dynamic solution would be better.
Cheers
First of all, thanks for the link to my blog. Second, let me see if I can't answer that for you. One of the reasons you're having trouble adding another button when you want to add a button is that in that example I left you with no way of retrieving the Title Bar View through the usual channels. Hence, let's fix it (and potentially let me write another blog post this coming weekend.)
Starting with the xml file, add an id attribute:
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:gravity="center_horizontal"
android:orientation="horizontal"
android:id="@+id/title_complex">
<!-- Stuff -->
</LinearLayout>
and here's code to show you how to get that button in there within your Activity (you'll have to add all the flair later):
LinearLayout layout = (LinearLayout) getWindow().findViewById(R.id.title_complex);
layout.addView(new Button(this));
and if you take a look, there's a non-descript button in the Title Bar (like I said, you'll have to add your own flair):
Due note, however, that I can't guarantee that the button will remain or won't remain on subsequent Activities. I haven't investigated it yet but this should get you started. And if you have any more questions, feel free to ask them here (more eyeballs) or on my blog.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With