The title/action bar ID in android? - android

I wanted to try out this funny title bar coloring, but it doesn't work for me as
getWindow().findViewById(android.R.id.title);
returns null. So I had a look at it with Hierarchy Viewer and found out that the view is called id/action_bar instead. But there's no R.id.action_bar (autocomplete doesn't offer it and there's nothing like this is R.java).
So now I'm doubly confused:
Is android.R.id.title sort of obsolete now (I'm using version 16 in my emulator)?
Where does id/action_bar come from?
What's the recommended and simple practice w.r.t. compatibility?
Should I get ActionBarSherlock? I originally just wanted to change the title bar color... not fool around with it a lot.

Use the code below to get the ActionBar's id:
val actionBarId = resources.getIdentifier("action_bar", "id", packageName)
And use findViewById you can find the action bar.
Then find the title from actionbar's children (in normal cases):
val actionbar = findViewById<ViewGroup>(actionBarId)
for (view in actionbar.children) {
if (view is TextView) {
// this is the titleView
}
}
However, if you just want to change the title view's text, just use getSupportActionBar:
supportActionBar?.apply {
// set title text
title = "Hello"
// set colored title text
val coloredTitle = SpannableString("Hello")
coloredTitle.setSpan(ForegroundColorSpan(Color.RED), 0, coloredTitle.length, 0)
title = coloredTitle
}

I would recommend using ActionBarSherlock if you're looking for compatibility with Android versions before API level 14 / Android 4.0.
Changing the background of the ActionBar is straightforward and is most easily done via styles. See the "Background" section of http://android-developers.blogspot.com/2011/04/customizing-action-bar.html
You can also change it via code. Put this in your onCreate():
GradientDrawable gradientDrawable = new GradientDrawable(GradientDrawable.Orientation.TOP_BOTTOM, new int[] {Color.RED, Color.GREEN});
getActionBar().setBackgroundDrawable(gradientDrawable);
Here is a screenshot of this code in action:

Related

How to change background colour of Leanback SearchSupportFragment Android

How can I change background colour of search support fragment in android leanback library. I have tried to find a public function to do the same just like in BrowseSupportFragment.
Try this:
val backgroundManager = BackgroundManager.getInstance(requireActivity())
val backgroundManager.attach(requireActivity().window)
backgroundManager?.color = Color.parseColor("#ff0000")
It works for the RowsSupportFragment, so I guess it works for search too

Programmatically change AppBar background color in Kotlin

I'm pretty new to Android development and completely new to Kotlin. I have an app with a navigation drawer, and am trying to change the color of the AppBarLayout based on what the user selects from the navigation drawer. I've tried a few different methods, and the closest I've come has been to change the toolbar color instead of the whole AppBar. This might be acceptable, but instead of actually setting it to the color I want, it always changes it to a dark grey.
when (item.itemId) {
R.id.nav_audit -> {
txtMain.text = "Audit"
toolbar.setBackgroundColor(R.color.colorAudit)
loadAudits()
}
R.id.nav_testing -> {
txtMain.text = "Testing"
toolbar.setBackgroundColor(R.color.colorTesting)
}
R.id.nav_workflow -> {
txtMain.text = "Workflow"
toolbar.setBackgroundColor(R.color.colorWorkflow)
}
R.id.nav_other -> {
txtMain.text = "Other"
toolbar.setBackgroundColor(R.color.colorPrimary)
}
}
I've also looked at possibly changing the theme, but it looks like it may not be easy to do that after the application has already loaded. Any thoughts are appreciated.
Besides changing the color of the Toolbar that you are already doing, one way to change the status bar in Kotlin is like this:
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
(activity as? AppCompatActivity)?.window?.statusBarColor =
ContextCompat.getColor(context, R.color. colorTesting)
}
You could do a method that returns the color depending on itemId

Android 5+ custom notification XML layout with RemoteViews, set correct icon tint for ImageButton

My app is using a custom Notification layout with RemoteViews.
To display text, the layout is using the following system styles:
android:TextAppearance.Material.Notification.Title
android:TextAppearance.Material.Notification
This works fine.
However, the TextAppearance style can't be used to set the value of android:tint, so I had to hardcode the color.
To my best knowledge, there's no special system style for setting notification ImageButton tint.
Hardcoded colors work fine on the current Android 5+ systems, but some users install custom ROMs with custom dark themes, and the notification looks wrong, i.e. black icons on black background.
Is there any way to get the system notification icon / imagebutton color, and apply it from an XML layout?
Or maybe there's another way to achieve this?
Sorry, But as per my knowledge custom ROM's have separate system designs,configurations and that are not official as well.
So,supporting Custom ROM without knowledge about its design is not possible.
And android APIs are for supporting official ROM's.
Hope it Helps!!
Try this example :
Definition for notification :
// Declare variable
public static Bitmap icon;
// Assign value but this line can be different depends on current
// android sdk vesion ...
icon = BitmapFactory.decodeResource(getApplicationContext().getResources(), R.drawable.YOUR_IMAGE);
mBuilder = new NotificationCompat.Builder(this);
mBuilder.setShowWhen(false);
mBuilder.setDefaults(Notification.DEFAULT_ALL);
mBuilder.setVisibility(NotificationCompat.VISIBILITY_PUBLIC);
mBuilder.setSmallIcon(R.drawable.image1); // One way to load img
mBuilder.setContentText("this text not visible");
mBuilder.setLargeIcon(icon);// This is the line
mBuilder.setPriority(Notification.PRIORITY_DEFAULT);
mBuilder.setContent(contentNotifySmall); // ORI
//mBuilder.setAutoCancel(false);
mBuilder.setCustomBigContentView(contentNotify);
I setup small and big variant for any case , this is important.
for background can you try these attributes...
app:backgroundTint="#color/pay"
---------Or-------------
android:tint="#color/white"
You can take textColor from TextAppearance_Compat_Notification_Title and add it as tint to an image programmatically like this
val remoteViews = RemoteViews(service.packageName, R.layout.notification_layout)
val icon = Icon.createWithResource(context, R.drawable.icon)
val attrs = intArrayOf(android.R.attr.textColor)
with(context.obtainStyledAttributes(R.style.TextAppearance_Compat_Notification_Title, attrs)) {
val iconColor = getColor(0, Color.GRAY)
icon.setTint(iconColor)
recycle()
}
remoteViews.setImageViewIcon(R.id.ibPlayPause, icon)
You can use a notificationlistenerservice to get an active notification. This returns a list of StatusBarNotifications, then just:
StatusBarNotifcation sBNotification = activeNotifications[0];
Notification notification = sBNotification.getNotification();
int argbColor = notification.color;
If you change ImageButton to ImageView in your layout you can update it with
RemoteViews remoteView = getRemoteViews(context);
// load base icon from res
Bitmap baseIcon = BitmapFactory.decodeResource(context.getResources(), R.drawable.base_icon);
// edit Bitmap baseIcon any way for your choose
Bitmap editedBitmap = ...
// update notification view with edited Bitmap
remoteView.setImageViewBitmap(R.id.button_icon, edited);
P.S. you can edit Bitmap like this:
https://stackoverflow.com/a/5935686/7630175 or any other way
Hope it's help

Action Bar messed up after using setTitle

I am trying to set the title of the actionBar in a activity. I have 3 layout views in one activity. Each View Layout shows a different state of the payment process. Now that I set the title, at one stage the actionbar background gets messed up. I wonder why.
This does not happen if I comment out the following line.
onClick() {
....
getActionBar().setTitle("Customer Payment");
....
In the onCreate of the activity I run the following to setup the actionbar background.
private void setupActionBar() {
Drawable backgroundColor;
switch (getIntent().getIntExtra(God.HOME_SCREEN_OPERATION,
God.INVALID_ID)) {
case God.OPERATION_RECHARGE:
getActionBar().setIcon(R.drawable.icon_mobile);
backgroundColor = new ColorDrawable(getResources().getColor(
R.color.RechargeBackgroundColor));
getActionBar().setBackgroundDrawable(backgroundColor);
mobileServiceSummary.setVisibility(View.VISIBLE);
serviceInfoLayout.setBackground(backgroundColor);
serviceInfoIcon.setImageResource(R.drawable.icon_mobile);
break;
case God.OPERATION_FACILITY:
getActionBar().setIcon(R.drawable.icon_facility);
backgroundColor = new ColorDrawable(getResources().getColor(
R.color.ToiletBackgroundColor));
getActionBar().setBackgroundDrawable(backgroundColor);
facilityServiceSummary.setVisibility(View.VISIBLE);
serviceInfoLayout.setBackground(backgroundColor);
serviceInfoIcon.setImageResource(R.drawable.icon_facility);
break;
case God.OPERATION_DTH:
getActionBar().setIcon(R.drawable.icon_dth);
backgroundColor = new ColorDrawable(getResources().getColor(
R.color.DthBackgroundColor));
getActionBar().setBackgroundDrawable(backgroundColor);
dthServiceSummary.setVisibility(View.VISIBLE);
serviceInfoLayout.setBackground(backgroundColor);
serviceInfoIcon.setImageResource(R.drawable.icon_dth);
break;
// case R.id.mseb_payment:
// getActionBar().setIcon(R.drawable.icon_mseb);
// msebServiceSummary.setVisibility(View.VISIBLE) ;
// break;
default:
break;
}
}
Some more code..
private void enableCustomerPayment() {
getActionBar().setTitle("Customer Payment");
getActionBar().setSubtitle(
"Pincode of customer needed for payment permission.");
getActionBar().setDisplayHomeAsUpEnabled(false);
getActionBar().setHomeButtonEnabled(false);
getActionBar().setDisplayShowCustomEnabled(false) ;
getActionBar().setDisplayUseLogoEnabled(false) ;
findViewById(R.id.next_button).setVisibility(View.GONE);
findViewById(R.id.payment_button).setVisibility(View.VISIBLE);
findViewById(R.id.done_button).setVisibility(View.GONE);
operatorLockLayout.setVisibility(View.GONE);
customerLoginAndConfirmationLayout.setVisibility(View.VISIBLE);
customerPaymentLayout.setVisibility(View.GONE);
customerConfirmLayout.setVisibility(View.VISIBLE);
// customerConfirmSpaceLayout.setVisibility(View.VISIBLE);
}
private void enablePaymentConfirmation() {
getActionBar().setTitle("Payment Confirmation");
getActionBar().setSubtitle("Thankyou for your payment.");
setupActionBar();
getActionBar().setDisplayHomeAsUpEnabled(false);
getActionBar().setHomeButtonEnabled(false);
findViewById(R.id.next_button).setVisibility(View.GONE);
findViewById(R.id.payment_button).setVisibility(View.GONE);
findViewById(R.id.done_button).setVisibility(View.VISIBLE);
operatorLockLayout.setVisibility(View.GONE);
customerLoginAndConfirmationLayout.setVisibility(View.VISIBLE);
customerPaymentLayout.setVisibility(View.VISIBLE);
customerConfirmLayout.setVisibility(View.GONE);
// customerConfirmSpaceLayout.setVisibility(View.GONE);
}
In styles.xml the color's are setup like this. And the colors are working fine.
<color name="NewWalletBackgroundColor">#FFD54E</color>
<color name="BalanceBackgroundColor">#FFD54E</color>
<color name="DepositBackgroundColor">#FFD54E</color>
<color name="MsebBackgroundColor">#E57272</color>
<color name="RechargeBackgroundColor">#81C784</color>
<color name="DthBackgroundColor">#AB6BAC</color>
<color name="ToiletBackgroundColor">#56C0ED</color>
The Action Bar is messed up
Here, the Action Bar background is completely blue. This is what I expect.
Edit
Seems like there is a issue with the height, it starts up with 96 and when its messed up the height is 0.
How do I fix this now ?
In my opinion the default action bar is expecting an icon for the navigation drawer icon on the right of action bar. I think there is a transparent button on the space you are talking about. Even if you set the drawer for this activity or not it will be there if you use default methods to set the action bar.First try these steps
setDrawerIndicatorEnabled(false).
actionBar.setDisplayHomeAsUpEnabled(false)
actionBar.setHomeButtonEnabled(false);
If that does not work go for a custom action bar.
Do something like this. Instead of using the default actionbar why do not you try to set a custom view (plain TextView where its width is set to match parent).
this.getActionBar().setDisplayShowCustomEnabled(true);
this.getActionBar().setDisplayShowTitleEnabled(false);
LayoutInflater inflator = LayoutInflater.from(this);
View v = inflator.inflate(R.layout.titleview, null);
//if you need to customize anything else about the text, do it here.
((TextView)v.findViewById(R.id.title)).setText(this.getTitle());
//assign the view to the actionbar
this.getActionBar().setCustomView(v);
I'm assuming from your question that the enablePaymentConfirmation is working code with getActionBar().setTitle("Customer Payment"); present and when it is commented out. If it too is playing up, then I will need to alter my answer.
Not seeing your xml makes it a bit more guess work, but from I can see, I would suggest the following.
1.
Call setupActionBar() from you OnCreate in your activity. This way it is set up for the duration of your activity. By not calling it in OnCreate if you call enableCustomerPayment() before enablePaymentConfirmation(), the actionbar setup will not have been called.
2.
Unless the following change in code you have not shown, these can go in your setupActionbar:
getActionBar().setDisplayHomeAsUpEnabled(false);
getActionBar().setHomeButtonEnabled(false);
3.
These are the two changes to the ActionBar between the two methods you show:
getActionBar().setDisplayShowCustomEnabled(false) ;
getActionBar().setDisplayUseLogoEnabled(false) ;
4.
I am not sure why you are only setting setDisplayShowCustomEnabled in your enableCustomerPayment(). I cannot see that you are using a customView.
- If not that can also go into your setup.
- Otherwise you will need to call it in all your methods with the changes.
- If you are using a custom view for your actionbar in some places and not others, this will be affecting how it is displayed. Particularly if you are not managing the bool changes.
5.
Same goes for the logo, I don't see where you are using it. So I would put it in setup. If you are using it for the others and you haven't got your xml set up correctly, it could be why there is a difference in the background color.
Hope this helps. Feel free to post more info, xml would be good.

TextColor of Xamarin.Forms SearchBar

I have a Xamarin.Forms SearchBar on a StackLayout with a dark background color.
By default the input field is dark as well, probably due to a transparent background. To modify the search bar background color there is a BackgroundColor property. (In the example below I set it to dark gray.)
But how to adjust the text color? There is no such property. And even with a custom search bar renderer I don't find a solution.
This is how it looks with just the placeholder:
...and with some input (black "Hello world!" on a pretty dark background):
Here is the code for an Android Custom renderer that will do the trick. I would upload a screenshot, but I don't have enough points yet :(
using System;
using Android.Widget;
using Android.Text;
using G = Android.Graphics;
using Xamarin.Forms;
using Xamarin.Forms.Platform.Android;
[assembly:ExportRenderer( typeof(MySearchBar), typeof(Some.Namespance.MySearchBar_Droid) )]
namespace Some.Namespace
{
public class MySearchBar_Droid : SearchBarRenderer
{
protected override void OnElementChanged( ElementChangedEventArgs<SearchBar> args )
{
base.OnElementChanged( args );
// Get native control (background set in shared code, but can use SetBackgroundColor here)
SearchView searchView = (base.Control as SearchView);
searchView.SetInputType( InputTypes.ClassText | InputTypes.TextVariationNormal );
// Access search textview within control
int textViewId = searchView.Context.Resources.GetIdentifier( "android:id/search_src_text", null, null );
EditText textView = (searchView.FindViewById( textViewId ) as EditText);
// Set custom colors
textView.SetBackgroundColor( G.Color.Rgb( 225, 225, 225 ) );
textView.SetTextColor( G.Color.Rgb( 32, 32, 32 ) );
textView.SetHintTextColor( G.Color.Rgb( 128, 128, 128 ) );
// Customize frame color
int frameId = searchView.Context.Resources.GetIdentifier( "android:id/search_plate", null, null );
Android.Views.View frameView = (searchView.FindViewById( frameId ) as Android.Views.View);
frameView.SetBackgroundColor( G.Color.Rgb( 96, 96, 96 ) );
}
}
}
You can achieve this by creating a custom View that has a bindable-property like ForegroundTextColor and then create a custom renderer.
In the custom renderer you can inherit from the platform specific renderer, i.e. on WindowsPhone it is:-
Xamarin.Forms.Platform.WinPhone.SearchBarRenderer
You can then monitor for property changes to the bindable-property you created and set the platform native control Text-color that is used to change the appearance of the non-editing view of the SearchBar.
You also have to monitor for IsFocused and apply the colouring on WindowsPhone, at least, also. This may also apply for other platforms possibly as well.
Update 1:-
========
In reply to your comment you don't have to render the whole SearchBar yourself.
If you inherit from the renderer you are able to customize things finer.
With specific reference to Android to achieve this you have to get reference to AutoCompleteTextView and then you can call SetTextColor to change the color.
Update 2:-
==========
SearchBar is a composite control in Android.
The AutoCompleteTextView is buried rather deep in the hierarchy.
On 4.4 this can be found using the following code. Other versions may well differ. This is by no means a good approach necessarily for production using ordinal indexes however:-
AutoCompleteTextView objAutoTextView = (AutoCompleteTextView)(((this.Control.GetChildAt(0) as ViewGroup).GetChildAt(2) as ViewGroup).GetChildAt(1) as ViewGroup).GetChildAt(0);
Where this is the renderer class.
You can then call objAutoTextView.SetTextColor with the color to achieve the change in color to the SearchBar foreground text.
I finally found a very simple solution:
I accidentally used the Android Theme #android:style/Theme.Holo.Light and modified all colors explicitly. But to get a bright text color on a search bar you better use #android:style/Theme.Holo.
It does not allow you to set the color very precisely, but changing it from black to white was all I needed in this case.
You can make the following changes in the xaml if you are using xaml to obtain the different text color of search bar on different platforms:
<SearchBar x:Name="Search"
Placeholder="Search"
TextChanged="SearchBar_OnTextChanged"
SearchButtonPressed="OnSearch" BackgroundColor="#19588F">
<SearchBar.TextColor>
<OnPlatform x:TypeArguments="Color">
<OnPlatform.iOS>
Black
</OnPlatform.iOS>
<OnPlatform.Android>
White
</OnPlatform.Android>
<OnPlatform.WinPhone>
White
</OnPlatform.WinPhone>
</OnPlatform>
</SearchBar.TextColor>
</SearchBar>
Here's how I did it, another way:
[assembly: ExportRenderer(typeof (CustomSearchBar), typeof (CustomSearchBarRenderer))]
namespace Bahai.Android.Renderers
{
public class CustomSearchBarRenderer : SearchBarRenderer
{
protected override void OnElementChanged(ElementChangedEventArgs<SearchBar> e)
{
base.OnElementChanged(e);
if (e.OldElement == null)
{
SearchBar element = (SearchBar) this.Element;
var native = (global::Android.Widget.SearchView) Control;
// do whatever you want to the controls here!
//--------------------------------------------
// element.BackgroundColor = Color.Transparent;
// native.SetBackgroundColor(element.BackgroundColor.ToAndroid());
// native.SetBackgroundColor(Color.White.ToAndroid());
//The text color of the SearchBar / SearchView
AutoCompleteTextView textField = (AutoCompleteTextView)
(((Control.GetChildAt(0) as ViewGroup)
.GetChildAt(2) as ViewGroup)
.GetChildAt(1) as ViewGroup)
.GetChildAt(0);
if (textField != null)
textField.SetTextColor(Color.White.ToAndroid());
}
}
}
}
SearchBar has a TextColor property. At least in Xamarin 5.
<SearchBar
TextColor="Black"
Text="{Binding SearchString}">

Categories

Resources