How to display custom view in ActionBar? - android

I want to display custom search in actionbar (I'm using ActionBarSherlock for that).
I got that:
But I want make custom layout (edittext field) to occupy the entire available width.
I've implemented custom layout as suggested here.
There is my custom layout search.xml:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
style="?attr/actionButtonStyle"
android:layout_width="fill_parent"
android:layout_height="match_parent"
android:layout_gravity="fill_horizontal"
android:focusable="true" >
<FrameLayout
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_gravity="center_vertical|fill_horizontal" >
<EditText
android:id="#+id/search_query"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_gravity="left|center"
android:background="#drawable/bg_search_edit_text"
android:imeOptions="actionSearch"
android:inputType="text" />
<ImageView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="right|center_vertical"
android:src="#drawable/ic_search_arrow" />
</FrameLayout>
</LinearLayout>
And in MyActivity:
ActionBar actionBar = getSupportActionBar();
actionBar.setDisplayHomeAsUpEnabled(true);
actionBar.setDisplayShowCustomEnabled(true);
actionBar.setDisplayShowTitleEnabled(false);
actionBar.setIcon(R.drawable.ic_action_search);
LayoutInflater inflator = (LayoutInflater) this .getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View v = inflator.inflate(R.layout.search, null);
actionBar.setCustomView(v);
How can I make custom layout to occupy all the available width of actionBar?
Help, please.

There is a trick for this. All you have to do is to use RelativeLayout instead of LinearLayout as the main container. It's important to have android:layout_gravity="fill_horizontal" set for it. That should do it.

I struggled with this myself, and tried Tomik's answer.
However, this didn't made the layout to full available width on start, only when you add something to the view.
You'll need to set the LayoutParams.FILL_PARENT when adding the view:
//I'm using actionbarsherlock, but it's the same.
LayoutParams layout = new LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.FILL_PARENT);
getSupportActionBar().setCustomView(overlay, layout);
This way it completely fills the available space. (You may need to use Tomik's solution too).

This is how it worked for me (from above answers it was showing both default title and my custom view also).
ActionBar.LayoutParams layout = new ActionBar.LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT);
// actionBar.setCustomView(view); //last view item must set to android:layout_alignParentRight="true" if few views are there
actionBar.setCustomView(view, layout); // layout param width=fill/match parent
actionBar.setDisplayShowCustomEnabled(true);//must other wise its not showing custom view.
What I noticed is that both setCustomView(view) and setCustomView(view,params) the view width=match/fill parent. setDisplayShowCustomEnabled (boolean showCustom)

The answers from Tomik and Peterdk work when you want your custom view to occupy the entire action bar, even hiding the native title.
But if you want your custom view to live side-by-side with the title (and fill all remaining space after the title is displayed), then may I refer you to the excellent answer from user Android-Developer here:
https://stackoverflow.com/a/16517395/614880
His code at bottom worked perfectly for me.

For example, you can define a layout file which contains a EditText element.
<?xml version="1.0" encoding="utf-8"?>
<EditText xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/searchfield"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:inputType="textFilter" >
</EditText>
you can do
public class MainActivity extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ActionBar actionBar = getActionBar();
// add the custom view to the action bar
actionBar.setCustomView(R.layout.actionbar_view);
EditText search = (EditText) actionBar.getCustomView().findViewById(R.id.searchfield);
search.setOnEditorActionListener(new OnEditorActionListener() {
#Override
public boolean onEditorAction(TextView v, int actionId,
KeyEvent event) {
Toast.makeText(MainActivity.this, "Search triggered",
Toast.LENGTH_LONG).show();
return false;
}
});
actionBar.setDisplayOptions(ActionBar.DISPLAY_SHOW_CUSTOM
| ActionBar.DISPLAY_SHOW_HOME);
}

There is an example in the launcher app of Android (that I've made a library out of it, here), inside the class that handles wallpapers-picking ("WallpaperPickerActivity") .
The example shows that you need to set a customized theme for this to work. Sadly, this worked for me only using the normal framework, and not the one of the support library.
Here're the themes:
styles.xml
<style name="Theme.WallpaperPicker" parent="Theme.WallpaperCropper">
<item name="android:windowBackground">#android:color/transparent</item>
<item name="android:colorBackgroundCacheHint">#null</item>
<item name="android:windowShowWallpaper">true</item>
</style>
<style name="Theme.WallpaperCropper" parent="#android:style/Theme.DeviceDefault">
<item name="android:actionBarStyle">#style/WallpaperCropperActionBar</item>
<item name="android:windowFullscreen">true</item>
<item name="android:windowActionBarOverlay">true</item>
</style>
<style name="WallpaperCropperActionBar" parent="#android:style/Widget.DeviceDefault.ActionBar">
<item name="android:displayOptions">showCustom</item>
<item name="android:background">#88000000</item>
</style>
value-v19/styles.xml
<style name="Theme.WallpaperCropper" parent="#android:style/Theme.DeviceDefault">
<item name="android:actionBarStyle">#style/WallpaperCropperActionBar</item>
<item name="android:windowFullscreen">true</item>
<item name="android:windowActionBarOverlay">true</item>
<item name="android:windowTranslucentNavigation">true</item>
</style>
<style name="Theme" parent="#android:style/Theme.DeviceDefault.Wallpaper.NoTitleBar">
<item name="android:windowTranslucentStatus">true</item>
<item name="android:windowTranslucentNavigation">true</item>
</style>
EDIT: there is a better way to do it, which works on the support library too. Just add this line of code instead of what I've written above:
getSupportActionBar().setDisplayShowCustomEnabled(true);

Related

Removing Extra Space in Custom ActionBar

My issue concerns using fully custom ActionBar views (as it's necessary for how my customer wants the ActionBar to work). I've removed the logo, title, and everything else possible. However, the custom view for the ActionBar will not extend all the way across the screen.
I've tried the following (as a quick overview):
Dynamically removing aspects of the ActionBar (snippet below)
Removing the Options Menu in its entirety
Specifying in the Style/Theme to remove everything from the ActionBar
Here is a screenshot of my issue:
Here is the style: (as a side note, I originally kept the native ActionBar but removed most of it)
<!-- Customized App Theme -->
<style name="AppTheme2" parent="Theme.AppCompat.Light">
<!-- Let the actioBbar overlay the activity, ie activity is full screen -->
<item name="android:windowActionBarOverlay">true</item>
<!-- Set up the action bar styles -->
<item name="android:actionBarStyle">#style/ActionBarEmpty</item>
<!-- Remove the shadow under the actionBar -->
<item name="android:windowContentOverlay">#null</item>
<!-- Set the drawer icon to show up instead of the "Up" caret icon
<item name="android:homeAsUpIndicator">#drawable/ic_drawer</item>
<item name="homeAsUpIndicator">#drawable/ic_drawer</item>
-->
<!-- Support library compatibility -->
<item name="actionBarStyle">#style/ActionBarEmpty</item>
</style>
<!-- Final, empty Action Bar style | makes space for customized actionBar -->
<style name="ActionBarEmpty" parent="Widget.AppCompat.Base.ActionBar">
<!-- TODO: Add support versions -->
<item name="android:displayOptions">none</item>
<item name="android:background">#color/transparent</item>
<!-- Tested the below, does absolute nothing -->
<item name="android:layout_margin">0dp</item>
<item name="android:padding">0dp</item>
<item name="android:minWidth">0dp</item>
</style>
Here is the code in my Activity that concerns setting up the ActionBar:
// Initialize and set up the ActionBar
mActionBar = getActionBar();
mActionBar.setDisplayHomeAsUpEnabled(false);
mActionBar.setDisplayShowHomeEnabled(false);
mActionBar.setDisplayShowTitleEnabled(false);
mActionBar.setDisplayShowCustomEnabled(true);
// Set the actionBar layout initially to the simple one
mActionBar.setCustomView(mViewActionBarSimple);
Here is the view shown in the screenshot for the ActionBar:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="horizontal"
android:layout_width="match_parent"
android:layout_height="?android:actionBarSize"
android:background="#color/white">
<ImageButton
android:id="#+id/navButton"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:paddingTop="#dimen/padding_actionbar_icon"
android:paddingBottom="#dimen/padding_actionbar_icon"
android:paddingRight="#dimen/padding_actionbar_icon"
android:paddingEnd="#dimen/padding_actionbar_icon"
android:layout_marginLeft="#dimen/margin_actionbar_icon_left"
android:layout_marginStart="#dimen/margin_actionbar_icon_left"
android:src="#drawable/ic_drawer_normal"
android:background="?android:attr/selectableItemBackground"
/>
<TextView
android:id="#+id/textTitle"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="#dimen/margin_general"
android:layout_gravity="center"
android:textColor="#color/black"
android:textSize="#dimen/text_normal"
android:text="#string/garbage_fill_short"
/>
</LinearLayout>
In addition to trying to remove everything I could think of, I also tried to remove the options menu:
#Override
public boolean onCreateOptionsMenu(Menu menu) {
return false;
}
#Override
public boolean onPrepareOptionsMenu(Menu menu) {
// To remove the options menu - and make the custom actionBar take the full space -
// always return false
return false;
}
I'm running this on a Samsung Galaxy S4 with Android KitKat.
Thank you for reading this. Any help would be appreciated at this point.
Update: For anyone reading this, I don't know why it worked like this, but I came upon the problem after following the below answer. I surrounded the actionBar layout with a RelativeLayout [with the LinearLayout and its contents as the children], and the width/background fixed itself... The answer is still amazing as its very clear cut and absolutely removes the actionBar, while before I was still using it in some way.
Please try below for removing action bar content by creating base activity so you can refer in all your app & inflate custom action bar from layout
#SuppressLint("InlinedApi")
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
getSupportActionBar().hide();
ActionBar actionBar = getSupportActionBar();
actionBar.setDisplayHomeAsUpEnabled(false);
actionBar.setDisplayShowCustomEnabled(true);
actionBar.setDisplayShowTitleEnabled(false);
actionBar.setDisplayShowHomeEnabled(false);
actionBar.setHomeButtonEnabled(false);
actionBar.setIcon(new ColorDrawable(getResources().getColor(android.R.color.transparent)));
View homeIcon = findViewById(android.R.id.home);
// Hides the View (and so the icon)
if (homeIcon != null)
((View) homeIcon.getParent()).setVisibility(View.GONE);
overridePendingTransition(0, 0);
}
add custom view
#SuppressLint("InlinedApi")
#Override
public void setContentView(int layoutResID)
{
super.setContentView(R.layout.activity_base);
ViewGroup viewGroup = (ViewGroup) findViewById(R.id.container);
viewGroup.removeAllViews();
viewGroup.addView(getLayoutInflater().inflate(layoutResID, null));
// you can find action_bar layouts view & add listner
}
and customise XML containing custom action bar in activity_base.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:layout_gravity="right"
android:orientation="vertical" >
<include layout="#layout/action_bar" />
<FrameLayout
android:id="#+id/container"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_gravity="right" />
</LinearLayout>
Where you want to use then extend this activity.

How to set a default layout in a theme

I'm using a custom titlebar in my app, but everytime I create a new layout I have to call:
<include
android:id="#+id/titlebar"
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="#integer/titlebar_weight"
layout="#layout/titlebar" />
Instead calling this in all the layouts how can I define it in a theme (in other words: define a default layout for the theme)?
My default layout:
Although the old title bar can be customized a bit via a theme (windowTitleStyle, windowTitleSize, windowTitleBackgroundStyle), you cannot set your own layout. Also the title bar was replaced by the ActionBar in Android 3.0, so that won't help you anyway.
Setting a default layout in a theme is not possible, at least I could not find a way to do it. But you still have several options to reduce repetition when adding your header layout:
Create a master layout with your header and a ViewStub for your content, then set the inflatedId by code.
Consider building your screens with fragments and add/remove them programmatically from your master layout.
Add the header programmatically in a base activity (suggested by user1527136)
Include it (that is what you are already doing, and it is not that bad imho)
I would recommend against creating the actionbar yourself, you can either try:
Actionbar Sherlock or ActionbarCompat (from the Google samples in your SDK).
<resources>
<style name="Theme.Transparent" parent="android:Theme">
<item name="android:windowIsTranslucent">true</item>
<item name="android:windowBackground">#android:color/transparent</item>
<item name="android:windowContentOverlay">#null</item>
<item name="android:windowNoTitle">true</item>
<item name="android:windowIsFloating">true</item>
<item name="android:backgroundDimEnabled">false</item>
</style>
</resources>
<activity
android:theme="#style/Theme.Transparent"
</activity>
I don't think this can be achieved through theming alone. You would need to create an abstract Activity that will include your title bar and wrap the content view set by the extended Activity classes. Here's an example:
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" >
<include
android:id="#+id/titleBar"
android:layout_width="match_parent"
android:layout_height="wrap_content"
layout="#layout/titlebar" />
<FrameLayout
android:id="#+id/content"
android:layout_width="match_parent"
android:layout_height="match_parent" />
</LinearLayout>
Abstract Activity
public abstract class TitleBarActivity extends Activity {
#Override
protected void onCreate( Bundle savedInstanceState ) {
super.onCreate( savedInstanceState );
super.setContentView( R.layout.title_bar_activity );
}
#Override
public void setContentView( int layoutResId ) {
FrameLayout contentFrameLayout = (FrameLayout) findViewById( R.id.content );
contentFrameLayout.removeAllViews();
getLayoutInflater().inflate( layoutResId, contentFrameLayout );
}
}
This is a very simple implementation, but should give you the general idea of what you need to do. Now for any Activity that extends TitleBarActivity, you'll already have the title bar at the top by default. Any customization of the title you want your activities to control, add methods in TitleBarActivity to do so.

Setting a custom share icon on Actionbar ShareActionProvider

I'm trying to set the icon ShareActionProvider, need a solid white one instead of the semi transparent white one.
However setting in share_menu.xml and code doesn't work. Just wondering whether anyone has got workaround for this before extending the ShareActionProvider. (I'm using actionbarsherlock)
#Override
public void onCreateOptionsMenu(final Menu menu, final MenuInflater inflater) {
inflater.inflate(R.menu.share_menu, menu);
MenuItem actionItem = menu.findItem(R.id.share_action_provider);
ShareActionProvider actionProvider = (ShareActionProvider) actionItem.getActionProvider();
actionProvider.setShareIntent(mShareIntent);
// re-setting the icon as it's not being picked up from the menu xml file
actionItem.setIcon(R.drawable.ic_action_share);
super.onCreateOptionsMenu(menu, inflater);
}
share_menu.xml
<item android:id="#+id/share_action_provider"
android:showAsAction="ifRoom"
android:title="#string/share_with"
android:icon="#drawable/ic_action_share"
android:actionProviderClass="com.actionbarsherlock.widget.ShareActionProvider" />
Update:
Also tried setting it in the style, but no joy
<style name="Theme.MyApp" parent="Theme.Sherlock.Light">
<item name="actionModeStyle">#style/ActionModeStyle</item>
<item name="android:actionModeStyle">#style/ActionModeStyle</item>
</style>
<style name="ActionModeStyle" parent="Widget.Sherlock.ActionMode">
<item name="actionModeShareDrawable">#drawable/ic_action_share</item>
</style>
When I am looking to customize the action bar, usually the first place I look is the ActionBarSherlock themes and styles.
I found that the Sherlock theme uses the "actionModeShareDrawable" as found in theme.xml file.
Try changing your theme to include the "actionModeShareDrawable" item directly.
<style name="Theme.MyApp" parent="Theme.Sherlock.Light">
<item name="actionModeShareDrawable">#drawable/ic_action_share</item>
</style>
For AppCompat the changes to 2 styles are needed:
1)
<style name="MyAppTheme" parent="#style/Theme.AppCompat.Light.DarkActionBar">
<item name="actionBarWidgetTheme">#style/Theme.AppCompat.CustomShareIcon</item>
<item name="android:actionBarWidgetTheme">#style/Theme.AppCompat.CustomShareIcon</item>
</style>
In other words, specifiing attr:actionModeShareDrawable in your MyAppTheme is not what you really need, but it should be mentioned in your attr:actionBarWidgetTheme as following:
2)
<style name="Theme.AppCompat.CustomShareIcon" parent="#style/Theme.AppCompat">
<item name="actionModeShareDrawable">#drawable/abc_ic_menu_share_holo_dark</item> <!-- your icon goes here -->
</style>
UPDATE: Forget about the TRICKY way below, just sub-class ShareActionProvider, return null in onCreateActionView Method, and provide your own icon in menu.xml file, everything will be fine
===========================
I found a very tricky but none-ActionBarSherlock-specific way:
Sub-class ShareActionProvider, with just a little tweak:
#Override
public View onCreateActionView() {
View target = super.onCreateActionView();
ViewGroup viewGroup = (ViewGroup) LayoutInflater.from(context).inflate(R.layout.actionbutton_share, null);
ImageView overlay = (ImageView) viewGroup.findViewById(R.id.overlay);
ViewGroup container = (ViewGroup) viewGroup.findViewById(R.id.container);
container.addView(target);
container.getLayoutParams().width = overlay.getLayoutParams().width;
container.getLayoutParams().height = overlay.getLayoutParams().height;
return viewGroup;
}
Create a layout file (R.layout.actionbutton_share), which place the original view at top but transparent to user (Note the "android:alpha=0" part) :
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:orientation="vertical" >
<FrameLayout
android:id="#+id/container"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:layout_centerVertical="true"
android:alpha="0" />
<ImageView
android:id="#+id/overlay"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:layout_centerVertical="true"
android:layout_marginLeft="7dp"
android:layout_marginRight="7dp"
android:src="#drawable/yours_whatever_share_icon"
tools:ignore="ContentDescription" />
</RelativeLayout>
Use the hacked ShareActionProvider in your menu.xml file
vivimice's solution is good, but the icon of last used app for sharing becomes hidden too.
I did custom share icon as a common menu item without any ShareActionProvider, just in onOptionsItemSelected() method used this code:
Intent sendIntent = new Intent();
sendIntent.setAction(Intent.ACTION_SEND);
sendIntent.putExtra(Intent.EXTRA_TEXT, "This is my text to send.");
sendIntent.setType("text/plain");
startActivity(Intent.createChooser(sendIntent, getResources().getText(R.string.send_to)));
It creates not a popup menu, but a chooser dialog.
You can override the non-public attribute like this.
<style name="Theme.MyApp" parent="android:Theme.Holo">
<item name="*android:actionModeShareDrawalbe">#drawable/icon</item>
</style>
(*) means reference to the non-public resources in Android

Creating a custom dialog in Android

I am trying to create a custom dialog in Android. But whatever I tried to do, I am not able to change the width of the dialog. It just remains the same. The following is the view that I am setting as the content for the dialog.
<RelativeLayout
android:id="#+id/current_stats"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:visibility="visible">
<ImageView android:id="#+id/player_image"
android:src="#drawable/person"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"/>
<TextView
android:id="#+id/player_name"
android:layout_below="#id/player_image"
android:layout_centerHorizontal="true"
android:text="Raja Ram"
android:layout_width="wrap_content"
android:layout_height="wrap_content"/>
<ImageButton android:id="#+id/dialog_close"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_alignParentRight="true"
android:background="#00000000"
android:src="#drawable/close_button_selector"/>
<ImageButton android:id="#+id/dialog_flip"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_alignParentLeft="true"
android:background="#00000000"
android:src="#drawable/rotate"/>
</RelativeLayout>
As you can see, everywhere I am using wrap_content in this code sample. Also I tried the following options
1) Setting a custom style while creating the Dialog like this.
dialog = new Dialog(this,R.style.Theme_Dialog);
And the style as follows
<resources>
<style name="Theme" parent="android:Theme">
</style>
<style name="Theme.Dialog">
<item name="android:layout_width">wrap_content</item>
<item name="android:layout_height">wrap_content</item>
<item name="android:windowIsFloating">true</item>
<item name="android:windowContentOverlay">#null</item>
<item name="android:windowAnimationStyle">#android:style/Animation.Dialog</item>
<item name="android:windowSoftInputMode">stateUnspecified|adjustPan</item>
</style>
</resources>
2) Setting the parameters for the view in the onCreateDialog() like this
LayoutInflater inflater = (LayoutInflater)this.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
v = inflater.inflate(R.layout.player_info, null, false);
ViewGroup.LayoutParams p = new ViewGroup.LayoutParams(ViewGroup.LayoutParams.FILL_PARENT,ViewGroup.LayoutParams.WRAP_CONTENT);
dialog.setContentView(v,p);
3) I also tried to set the Window parameters like this in the onCreateDialog() method
WindowManager.LayoutParams params = dialog.getWindow().getAttributes();
params.width=WindowManager.LayoutParams.WRAP_CONTENT;
dialog.getWindow().setAttributes(params);
But again no luck. Can someone help me out with this issue. Am I doing something wrong?? Also can you please suggest me how to set the x and y postions for the Dialog window?
Thanks
dialog = new Dialog(this,android.R.style.Theme_Translucent_NoTitleBar);
dialog.setContentView(R.layout.custom_dialog);
LayoutParams lp=dialog.getWindow().getAttributes();
lp.x=100;lp.y=100;lp.width=100;lp.height=200;lp.gravity=Gravity.TOP | Gravity.LEFT;
lp.dimAmount=0;
lp.flags=LayoutParams.FLAG_LAYOUT_NO_LIMITS | LayoutParams.FLAG_NOT_TOUCH_MODAL;
// dialog.getWindow().setAttributes(lp);
dialog.show();
This worked well for me....
Is your problem that it takes the full width of the screen, or that you can't control how much of the screen is it taking up?
To make your activity act as a dialog, and not take up the full with you should set your activity to have the dialog theme in the manifest:
<activity android:theme="#android:style/Theme.Dialog">
The dialog will be as large as is required by your layout. If you want it to be wider, you need to make your layout wider. (Adjust size of images, add padding, etc).
I'm not aware of a way to position the dialog window.. I think it is always centered, I could be wrong though.
I figured out the problem after a long time. The problem was with the way I used Relative layout. I guess I have not specified the relative position properly. When I changed that to linear layout it worked fine. It was not using up the whole screen but only whatever is required.
I could change the width,height and the position of the Dialog using getWindow().setAttributes(params)
in the onCreate() method of yout custom dialog class do the next
#Override
protected void onCreate(Bundle savedInstanceState) {
getWindow().setLayout(x, y);
}

Set title background color

In my android application I want the standard/basic title bar to change color.
To change the text color you have setTitleColor(int color), is there a way to change the background color of the bar?
This thread will get you started with building your own title bar in a xml file and using it in your activities
Edit
Here is a brief summary of the content of the link above - This is just to set the color of the text and the background of the title bar - no resizing, no buttons, just the simpliest sample
res/layout/mytitle.xml - This is the view that will represent the title bar
<?xml version="1.0" encoding="utf-8"?>
<TextView
xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/myTitle"
android:text="This is my new title"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:textColor="#color/titletextcolor"
/>
res/values/themes.xml - We want to keep the default android theme and just need to change the background color of the title background. So we create a theme that inherits the default theme and set the background style to our own style.
<?xml version="1.0" encoding="utf-8"?>
<resources>
<style name="customTheme" parent="android:Theme">
<item name="android:windowTitleBackgroundStyle">#style/WindowTitleBackground</item>
</style>
</resources>
res/values/styles.xml - This is where we set the theme to use the color we want for the title background
<?xml version="1.0" encoding="utf-8"?>
<resources>
<style name="WindowTitleBackground">
<item name="android:background">#color/titlebackgroundcolor</item>
</style>
</resources>
res/values/colors.xml - Set here the color you want
<?xml version="1.0" encoding="utf-8"?>
<resources>
<color name="titlebackgroundcolor">#3232CD</color>
<color name="titletextcolor">#FFFF00</color>
</resources>
In the AndroidMANIFEST.xml, set the theme attribute either in the application (for the whole application) or in the activity (only this activity) tags
<activity android:name=".CustomTitleBar" android:theme="#style/customTheme" ...
From the Activity (called CustomTitleBar) :
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_CUSTOM_TITLE);
setContentView(R.layout.main);
getWindow().setFeatureInt(Window.FEATURE_CUSTOM_TITLE, R.layout.mytitle);
}
Thanks for this clear explanation, however I would like to add a bit more to your answer by asking a linked question (don't really want to do a new post as this one is the basement on my question).
I'm declaring my titlebar in a Superclass from which, all my other activities are children, to have to change the color of the bar only once. I would like to also add an icon and change the text in the bar. I have done some testing, and managed to change either one or the other but not both at the same time (using setFeatureDrawable and setTitle).
The ideal solution would be of course to follow the explanation in the thread given in the link, but as i'm declaring in a superclass, i have an issue due to the layout in setContentView and the R.id.myCustomBar, because if i remember well i can call setContentView only once...
EDIT
Found my answer :
For those who, like me, like to work with superclasses because it's great for getting a menu available everywhere in an app, it works the same here.
Just add this to your superclass:
requestWindowFeature(Window.FEATURE_CUSTOM_TITLE);
setContentView(R.layout.customtitlebar);
getWindow().setFeatureInt(Window.FEATURE_CUSTOM_TITLE, R.layout.customtitlebar);
customTitleText = (TextView) findViewById(R.id.customtitlebar);
(you have to declare the textview as protected class variable)
And then the power of this is that, everywhere in you app (if for instance all your activities are children of this class), you just have to call
customTitleText.setText("Whatever you want in title");
and your titlebar will be edited.
The XML associated in my case is (R.layout.customtitlebar) :
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="horizontal" android:layout_width="fill_parent"
android:layout_height="fill_parent" android:background="#color/background">
<ImageView android:layout_width="25px" android:layout_height="25px"
android:src="#drawable/icontitlebar"></ImageView>
<TextView android:id="#+id/customtitlebar"
android:layout_width="wrap_content" android:layout_height="fill_parent"
android:text="" android:textColor="#color/textcolor" android:textStyle="bold"
android:background="#color/background" android:padding="3px" />
</LinearLayout>
There is another way to change the background color, however it is a hack and might fail on future versions of Android if the View hierarchy of the Window and its title is changed. However, the code won't crash, just miss setting the wanted color, in such a case.
In your Activity, like onCreate, do:
View titleView = getWindow().findViewById(android.R.id.title);
if (titleView != null) {
ViewParent parent = titleView.getParent();
if (parent != null && (parent instanceof View)) {
View parentView = (View)parent;
parentView.setBackgroundColor(Color.rgb(0x88, 0x33, 0x33));
}
}
This code helps to change the background of the title bar programmatically in Android. Change the color to any color you want.
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.your_layout);
getActionBar().setBackgroundDrawable(new ColorDrawable(Color.parseColor("#1c2833")));
}
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
View titleView = getWindow().findViewById(android.R.id.title);
if (titleView != null) {
ViewParent parent = titleView.getParent();
if (parent != null && (parent instanceof View)) {
View parentView = (View)parent;
parentView.setBackgroundColor(Color.RED);
}
}
on above code you can try you can use title instead of titlebar
this will affect on all activity in your application
I suppose no.
You can create titleless activity and create your own title bar in activity layout.
Check this, Line 63 and below:
getWindow().setFeatureInt(Window.FEATURE_CUSTOM_TITLE, R.layout.custom_title_1)
sets customview instead of default title view.
Take a peek in platforms/android-2.1/data/res/layout/screen.xml of the SDK. It seems to define a title there. You can frequently examine layouts like this and borrow the
style="?android:attr/windowTitleStyle"
styles which you can then use and override in your own TextViews.
You may be able to even select the title for direct tweaking by doing:
TextView title = (TextView)findViewById(android.R.id.title);
Try with the following code
View titleView = getWindow().findViewById(android.R.id.title);
if (titleView != null) {
ViewParent parent = titleView.getParent();
if (parent != null && (parent instanceof View)) {
View parentView = (View)parent;
parentView.setBackgroundColor(Color.RED);
}
}
also use this link its very useful : http://nathanael.hevenet.com/android-dev-changing-the-title-bar-background/
There is an easier alternative to change the color of the title bar, by using the v7 appcompat support library provided by Google.
See this link on how to to setup this support library: https://developer.android.com/tools/support-library/setup.html
Once you have done that, it's sufficient to add the following lines to your res/values/styles.xml file:
<style name="AppTheme" parent="AppBaseTheme">
<item name="android:actionBarStyle">#style/ActionBar</item>
</style>
<!-- Actionbar Theme -->
<style name="ActionBar" parent="Widget.AppCompat.Light.ActionBar.Solid.Inverse">
<item name="android:background">#color/titlebackgroundcolor</item>
</style>
(assuming that "titlebackgroundcolor" is defined in your res/values/colors.xml, e.g.:
<color name="titlebackgroundcolor">#0000AA</color>
)
I have done this by changing style color values in "res" -> "values" -> "colors.xml"
This will change colors for entire project which is fine with me.
Things seem to have gotten better/easier since Android 5.0 (API level 21).
I think what you're looking for is something like this:
<style name="AppTheme" parent="AppBaseTheme">
<!-- Top-top notification/status bar color: -->
<!--<item name="colorPrimaryDark">#000000</item>-->
<!-- App bar color: -->
<item name="colorPrimary">#0000FF</item>
</style>
See here for reference:
https://developer.android.com/training/material/theme.html#ColorPalette
Paste this code after setContentView or into onCreate
if you have a color code use this ;
getSupportActionBar().setBackgroundDrawable(new ColorDrawable(Color.parseColor("#408ed4")));
if you want a specific code from Color library use this ;
getSupportActionBar().setBackgroundDrawable(new ColorDrawable(Color.WHITE));
you can use it.
toolbar.setTitleTextColor(getResources().getColor(R.color.white));

Categories

Resources