Change TimePicker text color - android

I've been trying to change the textcolor of my timepicker. But I can't find where the parent style is located. I've tried both
<style name="MyTimePicker" parent="#android:style/Widget.Holo.TimePicker">
<item name="android:textColor">#color/text</item>
</style>
and
<style name="MyTimePicker" parent="#android:style/Widget.TimePicker">
<item name="android:textColor">#color/text</item>
</style>
My minSdkVersion is 15. My targetSdkVersion is 20. I have rebuilded and cleaned my project.
I think I've been through every similar question on SO and none of them really have provided a solution for me. The only answer that might work is using some sort of library, but I'm not a big fan of that solution. Is the path to the parent something different from what I'm using, because I'm pretty sure I should be able to access it somehow?
Edit
This is how the theme is applied;
<TimePicker
style="#style/MyTimePicker"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/timePicker"
android:layout_below="#+id/textView"
android:layout_centerHorizontal="true" />
On a note this is the error I receive (forgot to place it before):
Error:Error retrieving parent for item: No resource found that matches the given name '#android:style/Widget.Holo.TimePicker'.
Edit 2
A couple of the questions I've viewed to try to solve this:
How can I override TimePicker to change text color - I think this question gets as close to an answer, but I'm not entirely sure what I need to do? Do I need to import the android TimePicker style into my project?
https://stackoverflow.com/questions/24973586/set-textcolor-for-timepicker-in-customized-app-theme - No answer is given.
How can i change the textcolor of my timepicker and datepicker? - Tried the 0 votes answer, but it didn't work.
How to change the default color of DatePicker and TimePicker dialog in Android? - Again can't find the TimePicker in a similar way.
Android - How do I change the textColor in a TimePicker? - Again, can't find the actual TimePicker parent.
These are probably the best questions/answers to my problem, but none of them help me. It would be nice to get a definitive answer on this.

I have combined Paul Burke's Answer and Simon's Answer to succesfully edit the text colour of the TimePicker.
Here's how it is accomplished:
TimePicker time_picker; //Instantiated in onCreate()
Resources system;
private void set_timepicker_text_colour(){
system = Resources.getSystem();
int hour_numberpicker_id = system.getIdentifier("hour", "id", "android");
int minute_numberpicker_id = system.getIdentifier("minute", "id", "android");
int ampm_numberpicker_id = system.getIdentifier("amPm", "id", "android");
NumberPicker hour_numberpicker = (NumberPicker) time_picker.findViewById(hour_numberpicker_id);
NumberPicker minute_numberpicker = (NumberPicker) time_picker.findViewById(minute_numberpicker_id);
NumberPicker ampm_numberpicker = (NumberPicker) time_picker.findViewById(ampm_numberpicker_id);
set_numberpicker_text_colour(hour_numberpicker);
set_numberpicker_text_colour(minute_numberpicker);
set_numberpicker_text_colour(ampm_numberpicker);
}
private void set_numberpicker_text_colour(NumberPicker number_picker){
final int count = number_picker.getChildCount();
final int color = getResources().getColor(R.color.text);
for(int i = 0; i < count; i++){
View child = number_picker.getChildAt(i);
try{
Field wheelpaint_field = number_picker.getClass().getDeclaredField("mSelectorWheelPaint");
wheelpaint_field.setAccessible(true);
((Paint)wheelpaint_field.get(number_picker)).setColor(color);
((EditText)child).setTextColor(color);
number_picker.invalidate();
}
catch(NoSuchFieldException e){
Log.w("setNumberPickerTextColor", e);
}
catch(IllegalAccessException e){
Log.w("setNumberPickerTextColor", e);
}
catch(IllegalArgumentException e){
Log.w("setNumberPickerTextColor", e);
}
}
}
Please note that this answer might be outdated by now. I ran into this a while ago with something that might have been buggy (see my question for more details). Otherwise you should probably follow Vikram's answer.

Not sure why you would need to dive into Java Reflection API for this. Its a simple styling matter. The attribute that you need to override is: textColorPrimary.
<style name="AppTheme" parent="#android:style/Theme.Holo.Light">
....
<item name="android:textColorPrimary">#ff0000</item>
</style>
If you're using the TimePicker inside a Dialog, override android:textColorPrimary in the dialog's theme.
That's about it.

A TimePicker is really just two NumberPickers. Looking into the Widget.NumberPicker style and layout, you'll find the it uses
#style/TextAppearance.Large.Inverse.NumberPickerInputText
Unfortunately, TextAppearance.Large.Inverse.NumberPickerInputText doesn't use one of the attributes that you can set in your theme. So you have two options:
Copy the necessary classes to make your own version of NumberPicker and TimePicker. (You might be able to extract something from libraries like HoloEverywhere)
Use hacks.
If you want to go the second route, you can do this:
private int mNumberPickerInputId = 0;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Resources system = Resources.getSystem();
// This is the internal id of the EditText used in NumberPicker (hack)
mNumberPickerInputId =
system.getIdentifier("numberpicker_input", "id", "android");
// just used for full example, use your TimePicker
TimePicker timePicker = new TimePicker(this);
setContentView(timePicker);
final int hourSpinnerId =
system.getIdentifier("hour", "id", "android");
View hourSpinner = timePicker.findViewById(hourSpinnerId);
if (hourSpinner != null) {
setNumberPickerTextColor(hourSpinner, Color.BLUE);
}
final int minSpinnerId =
system.getIdentifier("minute", "id", "android");
View minSpinner = timePicker.findViewById(minSpinnerId);
if (minSpinner != null) {
setNumberPickerTextColor(minSpinner, Color.BLUE);
}
final int amPmSpinnerId =
system.getIdentifier("amPm", "id", "android");
View amPmSpinner = timePicker.findViewById(amPmSpinnerId);
if (amPmSpinner != null) {
setNumberPickerTextColor(amPmSpinner, Color.BLUE);
}
}
private void setNumberPickerTextColor(View spinner, int color) {
TextView input = (TextView) spinner.findViewById(mNumberPickerInputId);
input.setTextColor(color);
}
EDIT
Upon further investigation, this hack doesn't really work well. It won't allow you to change the color of the NumberPicker above/below values. The color also resets after the use interacts with it. It seems that your only option will be to create your own copies of the necessary classes (option #1 above).

Adding to Vikram answer , Set the theme to timePicker do not set it as style
in styles.xml
<style name="timePickerOrange">
<item name="android:textColorPrimary">#color/orange</item> <!-- color for digits -->
<item name="android:textColor">#color/orange</item> <!-- color for colon -->
<item name="android:colorControlNormal">#color/orange</item> <!-- color for (horizontal) delimeters -->
</style>
and for timePicker
<TimePicker
android:theme="#style/timePickerOrange"
android:id="#+id/timePicker_defaultTime"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:fontFamily="#font/hero_regular"
android:timePickerMode="spinner"
app:fontFamily="#font/hero_regular" />

#Vikram is right
This is so simple.You can try this way
<style name="abirStyle" parent="#android:style/Theme.Holo.Light.Dialog.NoActionBar">
<item name="android:textColor">#color/colorPrimary</item>
<item name="android:background">#null</item>
<item name="android:textColorPrimary">#color/colorPrimary</item>
</style>

You can try to set android:textColorPrimaryInverse and android:textColorSecondaryInverse. That should do the job without using Reflection.
<style name="AppTheme" parent="Theme.AppCompat.Light.NoActionBar">
<item name="android:textColorPrimaryInverse">#android:color/black</item>
<item name="android:textColorSecondaryInverse">#color/colorLightGrey</item>
</style>

For those using the spinner, this is an easy way to change the colors and even provides the appropriate shadow effect of the previous and next numbers. Spinner requires a theme because most of the default xml attributes for colors only effect the clock mode.
styles.xml
<style name="timepicker">
<item name="android:textColorSecondary">#color/white </item>
<item name="android:textColorPrimary">#color/white </item>
</style>
xml layout file
<TimePicker
android:id="#+id/timePicker1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:theme="#style/timepicker"
android:layout_below="#id/line1"
android:layout_centerHorizontal="true"
android:padding="15dp"
android:timePickerMode="spinner" />

Related

How to read a TextAppearance attribute programmatically [duplicate]

Currently I'm using either a WebView or a TextView to show some dynamic data coming from a webservice in one of my apps.
If the data contains pure text, it uses the TextView and applies a style from styles.xml.
If the data contains HTML (mostly text and images) it uses the WebView.
However, this WebView is unstyled. Therefor it looks a lot different from the usual TextView.
I've read that it's possible to style the text in a WebView simply by inserting some HTML directly into the data. This sounds easy enough, but I would like to use the data from my Styles.xml as the values required in this HTML so I won't need to change the colors et cetera on two locations if I change my styles.
So, how would I be able to do this? I've done some extensive searching but I have found no way of actually retrieving the different style attributes from your styles.xml. Am I missing something here or is it really not possible to retrieve these values?
The style I'm trying to get the data from is the following:
<style name="font4">
<item name="android:layout_width">fill_parent</item>
<item name="android:layout_height">wrap_content</item>
<item name="android:textSize">14sp</item>
<item name="android:textColor">#E3691B</item>
<item name="android:paddingLeft">5dp</item>
<item name="android:paddingRight">10dp</item>
<item name="android:layout_marginTop">10dp</item>
<item name="android:textStyle">bold</item>
</style>
I'm mainly interested in the textSize and textColor.
It is possible to retrieve custom styles from styles.xml programmatically.
Define some arbitrary style in styles.xml:
<style name="MyCustomStyle">
<item name="android:textColor">#efefef</item>
<item name="android:background">#ffffff</item>
<item name="android:text">This is my text</item>
</style>
Now, retrieve the styles like this
// The attributes you want retrieved
int[] attrs = {android.R.attr.textColor, android.R.attr.background, android.R.attr.text};
// Parse MyCustomStyle, using Context.obtainStyledAttributes()
TypedArray ta = obtainStyledAttributes(R.style.MyCustomStyle, attrs);
// Fetch the text from your style like this.
String text = ta.getString(2);
// Fetching the colors defined in your style
int textColor = ta.getColor(0, Color.BLACK);
int backgroundColor = ta.getColor(1, Color.BLACK);
// Do some logging to see if we have retrieved correct values
Log.i("Retrieved text:", text);
Log.i("Retrieved textColor as hex:", Integer.toHexString(textColor));
Log.i("Retrieved background as hex:", Integer.toHexString(backgroundColor));
// OH, and don't forget to recycle the TypedArray
ta.recycle()
The answer #Ole has given seems to break when using certain attributes, such as shadowColor, shadowDx, shadowDy, shadowRadius (these are only a few I found, there might be more)
I have no idea as to why this issue occurs, which I am asking about here, but #AntoineMarques coding style seems to solve the issue.
To make this work with any attribute it would be something like this
First, define a stylable to contain the resource ids like so
attrs.xml
<resources>
<declare-styleable name="MyStyle" >
<attr name="android:textColor" />
<attr name="android:background" />
<attr name="android:text" />
</declare-styleable>
</resources>
Then in code you would do this to get the text.
TypedArray ta = obtainStyledAttributes(R.style.MyCustomStyle, R.styleable.MyStyle);
String text = ta.getString(R.styleable.MyStyle_android_text);
The advantage of using this method is, you are retrieving the value by name and not an index.
The answers from Ole and PrivatMamtora didn't work well for me, but this did.
Let's say I wanted to read this style programmatically:
<style name="Footnote">
<item name="android:fontFamily">#font/some_font</item>
<item name="android:textSize">14sp</item>
<item name="android:textColor">#color/black</item>
</style>
I could do it like this:
fun getTextColorSizeAndFontFromStyle(
context: Context,
textAppearanceResource: Int // Can be any style in styles.xml like R.style.Footnote
) {
val typedArray = context.obtainStyledAttributes(
textAppearanceResource,
R.styleable.TextAppearance // These are added to your project automatically.
)
val textColor = typedArray.getColorStateList(
R.styleable.TextAppearance_android_textColor
)
val textSize = typedArray.getDimensionPixelSize(
R.styleable.TextAppearance_android_textSize
)
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
val typeface = typedArray.getFont(R.styleable.TextAppearance_android_fontFamily)
// Do something with the typeface...
} else {
val fontFamily = typedArray.getString(R.styleable.TextAppearance_fontFamily)
?: when (typedArray.getInt(R.styleable.TextAppearance_android_typeface, 0)) {
1 -> "sans"
2 -> "serif"
3 -> "monospace"
else -> null
}
// Do something with the fontFamily...
}
typedArray.recycle()
}
I took some inspiration from Android's TextAppearanceSpan class, you can find it here: https://android.googlesource.com/platform/frameworks/base/+/master/core/java/android/text/style/TextAppearanceSpan.java
I was not able to get the earlier solutions to work.
My style is:
<style name="Widget.TextView.NumPadKey.Klondike" parent="Widget.TextView.NumPadKey">
<item name="android:textSize">12sp</item>
<item name="android:fontFamily">sans-serif</item>
<item name="android:textColor">?attr/wallpaperTextColorSecondary</item>
<item name="android:paddingBottom">0dp</item>
</style>
The obtainStyledAttributes() for android.R.attr.textSize gives String results of "12sp" which I then have to parse. For android.R.attr.textColor it gave a resource file XML name. This was much too cumbersome.
Instead, I found an easy way using ContextThemeWrapper.
TextView sample = new TextView(new ContextThemeWrapper(getContext(), R.style.Widget_TextView_NumPadKey_Klondike), null, 0);
This gave me a fully-styled TextView to query for anything I want. For example:
float textSize = sample.getTextSize();
With Kotlin, if you include the androidx.core:core-ktx library in your app/library...
implementation("androidx.core:core-ktx:1.6.0") // Note the -ktx
...you can have either of the following (no need for you to recycle the TypedArray):
// Your desired attribute IDs
val attributes = intArrayOf(R.attr.myAttr1, R.attr.myAttr2, android.R.attr.text)
context.withStyledAttributes(R.style.MyStyle, attributes) {
val intExample = getInt(R.styleable.MyIntAttrName, 0)
val floatExample = getFloat(R.styleable.MyFloatAttrName, 0f)
val enumExample = R.styleable.MyEnumAttrName, MyEnum.ENUM_1 // See Note 1 below
// Similarly, getColor(), getBoolean(), etc.
}
context.withStyledAttributes(R.style.MyStyle, R.styleable.MyStyleable) {
// Like above
}
// attributeSet is provided to you like in the constructor of a custom view
context.withStyledAttributes(attributeSet, R.styleable.MyStyleable) {
// Like above
}
Note 1 (thanks to this answer)
For getting an enum value you can define this extension function:
internal inline fun <reified T : Enum<T>> TypedArray.getEnum(index: Int, default: T) =
getInt(index, -1).let { if (it >= 0) enumValues<T>()[it] else default }
Note 2
The difference between -ktx dependencies like androidx.core:core and androidx.core:core-ktx is that the -ktx variant includes useful extension functions for Kotlin.
Otherwise, they are the same.
Also, thanks to the answer by Ole.
If accepted solution not working for try to rename attr.xml to attrs.xml (worked for me)

Android: Change color of Switch that is added dynamically

Android beginner here, so please bear with me...
I'm using a drawer where the menu items are added dynamically.Currently, this is what my code looks like:
val menu = nav_view.menu
menu.clear()
val selectedCatalogIsEmpty = selectedCatalogs.isEmpty()
for (catalog in catalogs){
val menuItem = menu.add(R.id.catalog_items, Menu.FIRST + catalog.catalogId, Menu.NONE, catalog.catalogName)
val switch = Switch(applicationContext)
menuItem.actionView = switch
if(selectedCatalogIsEmpty ||
selectedCatalogs.contains(catalog.catalogId) ) {
menuItem.isChecked = true
switch.isChecked = true
if(selectedCatalogIsEmpty){
selectedCatalogs.add(catalog.catalogId)
}
}
switch.setOnCheckedChangeListener { _, isChecked -> menuItem.isChecked = isChecked }
}
val menuItemSettings = menu.add(R.id.settings, Menu.NONE+ 5000, Menu.NONE, "Settings" )
Now, what i'd like to do is change the color of the thum when in the selected state. In order to achieve that, I've added the following to the styles.xml file:
<!-- Base application theme. -->
<style name="AppTheme" parent="Theme.AppCompat.Light.NoActionBar">
<!-- Customize your theme here. -->
<item name="colorPrimary">#color/colorPrimary</item>
<item name="colorPrimaryDark">#color/colorPrimaryDark</item>
<item name="colorAccent">#color/colorPrimary</item>
<item name="colorControlNormal">#color/colorWhite</item>
<item name="colorControlActivated">#color/colorPrimary</item>
</style>
Unfortunately, I'm still getting the wrong color during runtime. Instead of the blue. I'm getting a greeny thumb:
It's clear that I've completely missed the point...I've run a couple of searches and people suggest using the SwitchCompat instead of the Switch. I've tried doing that, but I must also be missing something because I've ended up seing the text in really small caps (instead of the thumb I get with the Switch view).
Thanks.
Regards,
Luis
Ok, so after more than 3 hours, I've finally found my bug: I was using the applicationContext to initialize the Switch and application's theme isn't initialized: it's only used to apply a default theme for the remaining activities. So, updating the Switch instantiation to something like this solves the problem:
val switch = Switch(this#MainActivity) //kotlin ref to my activity

How to get rid of the default background of the Android DatePickerDialog in Android 4.4.4?

I have a Xamarin.Android project targeting API 25 and having API 19 as the minimum SDK, in one of the activities when a button is touched the following DatePickerDialog appears:
As you can see, I defined a custom drawable with rounded corner and used it in the DatePickerDialog. The issue is that I can't get rid of the default background that has a shadowed border when running my application on an Android 4.4.4 device(API 19).
On Android N device (API 25) everything seem to work properly, here is a screenshot:
I would like to know how to remove the default background in Android 4.4.4 devices, is there any useful xml style attribute? Or maybe a programmatic solution? I can't find any resource discussing this issue.
Details
DatePickerFragment implementation that I am using:
public class DatePickerFragment : Android.Support.V4.App.DialogFragment,
Android.App.DatePickerDialog.IOnDateSetListener
{
public static readonly string TAG = "X:" + typeof(DatePickerFragment).Name.ToUpper();
Action<DateTime> _dateSelectedHandler = delegate { };
public static DatePickerFragment NewInstance(Action<DateTime> onDateSelected)
{
DatePickerFragment frag = new DatePickerFragment();
frag._dateSelectedHandler = onDateSelected;
return frag;
}
public override Dialog OnCreateDialog(Bundle savedInstanceState)
{
DateTime currently = DateTime.Now;
DatePickerDialog dialog = new DatePickerDialog(Activity,
Resource.Style.MyDialogTheme,
this,
currently.Year,
currently.Month,
currently.Day);
dialog.SetTitle("");
return dialog;
}
public void OnDateSet(DatePicker view, int year, int monthOfYear, int dayOfMonth)
{
DateTime selectedDate = new DateTime(year, monthOfYear + 1, dayOfMonth);
_dateSelectedHandler(selectedDate);
}
}
Style applied to the DatePickerDialog
<style name="MyDialogTheme" parent="Theme.AppCompat.Light.Dialog">
<item name="android:windowFrame">#null</item>
<item name="android:windowIsFloating">true</item>
<item name="android:windowContentOverlay">#null</item>
<item name="android:windowBackground">#color/transparent</item>
<item name="android:windowFrame">#color/transparent</item>
<item name="android:colorBackgroundCacheHint">#null</item>
<item name="android:background">#drawable/dialog_background</item>
<item name="android:datePickerStyle">#style/MyDatePicker</item>
<item name="android:backgroundDimEnabled">true</item>
</style>
dialog_background drawable
<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android" >
<stroke android:width="3dp"
android:color="#color/white" />
<corners android:radius="10dp" />
<solid android:color="#color/white" />
</shape>
MyDatePicker style definition
<style name="MyDatePicker" parent="android:Widget.Material.DatePicker">
<item name="android:datePickerMode">spinner</item>
</style>
The issue is that I can't get rid of the default background that has a shadowed border when running my application on an Android 4.4.4 device(API 19).
On Android N device (API 25) everything seem to work properly.
It seems that in your values\styles.xml file, Theme.AppCompat.Light.Dialog theme in material design support library is not working properly with DatePickerDialog.
Your MyDialogTheme parent theme is Theme.AppCompat.Light.Dialog,
maybe this theme does not work properly for all android versions, it works for Lollipop and above but does not work for KitKat.
To make it work for both versions you could do this :
Create a different folder for values-v21, copy your MyDialogTheme style to values-v21\styles.xml file, then it will work properly on Android API 21+.
In your values\styles.xml file, define a correct parent of the dialog to make sure it works properly on Android API 19. If you copy MyDialogTheme style to values-v21\styles.xml file and delete MyDialogTheme style in values\styles.xml, effect on Android API 19 like this, maybe this is the effect you want to achieve.
I was able to work around this issue by implementing custom dialogs.
By sub-classing the Dialog class, we can create custom dialogs that loads arbitrary axml layout files.
This requires you to create an axml layout and to define a class, which is obviously more work.
Here is the date picker dialog class I created:
public class CustomDatePickerDialog : Dialog
{
private AltRegisterFormActivity _owner;
public CustomDatePickerDialog(Context context, int styleId, DateTime birthDate) : base(context, styleId)
{
_owner = context as AltRegisterFormActivity;
SetTitle("");
SetContentView(Resource.Layout.DatePickerDialog);
FindViewById<DatePicker>(Resource.Id.DialogDatePicker).MaxDate = _getTimeStamp(DateTime.UtcNow.Year - 3);
FindViewById<DatePicker>(Resource.Id.DialogDatePicker).MinDate = _getTimeStamp(1920);
FindViewById<DatePicker>(Resource.Id.DialogDatePicker).DateTime = birthDate;
FindViewById<Button>(Resource.Id.DialogOkButton).Click += (_, __) =>
{
_owner.UISyncContext.Send((state) =>
{
_owner.SetDate(FindViewById<DatePicker>(Resource.Id.DialogDatePicker).DateTime);
Hide();
}, null);
};
FindViewById<Button>(Resource.Id.DialogCancelButton).Click += (_, __) =>
{
_owner.UISyncContext.Send((state) =>
{
Hide();
}, null);
};
}
private long _getTimeStamp(int year)
{
return Convert.ToInt64(new DateTime(year, 1, 1).Subtract(new DateTime(1970, 1, 1)).TotalMilliseconds);
}
}
CustomDatePickerDialog's constructor takes a styleId argument that allows to pass the desired style Id.
And here is the Resource.Layout.DatePickerDialog layout file:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:padding="#dimen/date_picker_dialog_padding">
<DatePicker
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/DialogDatePicker"
android:datePickerMode="spinner"
android:calendarViewShown="false" />
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal"
android:padding="0dp">
<View
android:layout_width="1dp"
android:layout_height="0dp"
android:layout_weight="1" />
<Button
android:text="CANCEL"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/DialogCancelButton"
android:background="#null"
android:fontFamily="sans-serif-regular"
android:textSize="13dp"
android:textStyle="bold" />
<Button
android:text="OK"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/DialogOkButton"
android:background="#null"
android:fontFamily="sans-serif-regular"
android:textSize="13dp"
android:textStyle="bold" />
</LinearLayout>
</LinearLayout>
The previous custom dialog will have almost the same look and feel whether it is displayed in a Kitkat or Lollipop+ device.

Remove SearchView search voice button line

Thanks to other SO related posts regarding SearchView customisation I was able to customise my SearchView to this point:
Now I'm trying to add voice search and I was able to change the voice button background resource:
int searchVoiceIconId = searchPlate.getContext().getResources().getIdentifier("android:id/search_voice_btn", null, null);
ImageView searchVoiceIcon = (ImageView) searchView.findViewById(searchVoiceIconId);
searchVoiceIcon.setImageResource(R.drawable.ic_action_mic);
searchVoiceIcon.setBackgroundColor(Color.TRANSPARENT);
However, I can't seem to get rid of the line under the voice search button.
any suggestions????
Thanks
This is a late reply but it might be helpful for future.
Add the following line:
<style name="AppTheme.SearchView" parent="Widget.AppCompat.SearchView">
<!-- Gets rid of the "underline" in the mic button-->
<item name="submitBackground">#null</item>
To your values/styles.xml file and it will remove the line.
Code:
((LinearLayout)search.findViewById(R.id.search_voice_btn).getParent()).setBackgroundColor(Color.TRANSPARENT);
int submitAreaId = searchView.getContext().getResources()
.getIdentifier("android:id/submit_area", null, null);
View submitAreaView = searchView.findViewById(submitAreaId);
if (submitAreaView != null) {
submitAreaView.setBackgroundColor(Color.parseColor("#00000000"));
}
This should remove any underline of the non text input area.

Theme change doesn't work on <4.0 as it should

I have some difficulties with setting up a "theme switcher" programmatically.
I would like to switch themes from app (between White (Theme.Light.NoTitleBar) and Dark (Theme.Black.NoTitleBar)) and what I do is:
I set a SharedPreference:
final String PREFS_NAME = "MyPrefsFile";
final SharedPreferences settings = getSharedPreferences(PREFS_NAME, 0);
final SharedPreferences.Editor editor = settings.edit();
and than I have a two buttons to switch themes (second one is almost identical)
Button ThemeWhite = (Button) findViewById(R.id.ThemeWhite);
ThemeWhite.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
editor.putBoolean("Theme", false);
editor.commit();
System.exit(2);
}
});
and in begging of each activity I check SharedPreference
boolean theme = settings.getBoolean("Theme", false);
if(theme){
this.setTheme(R.style.Theme_NoBarBlack);
} else{
this.setTheme(R.style.Theme_NoBar);
}
setContentView(R.layout.aplikacja);
I define themes in file styles.xml in folder values:
<resources>
<style name="Theme.NoBar" parent="#android:style/Theme.Light.NoTitleBar" />
<style name="Theme.NoBarBlack" parent="#android:style/Theme.NoTitleBar" />
in values-v11:
<resources>
<style name="Theme.NoBar" parent="#android:style/Theme.Holo.Light.NoActionBar" />
<style name="Theme.NoBarBlack" parent="#android:style/Theme.Holo.NoActionBar" />
in values-v14:
<resources>
<style name="Theme.NoBar" parent="#android:style/Theme.DeviceDefault.Light.NoActionBar" />
<style name="Theme.NoBarBlack" parent="#android:style/Theme.DeviceDefault.NoActionBar" />
manifest file:
<application
...
android:theme="#style/Theme.NoBar" >
Everything is working excellent on android >4.0 but when I use 2.2 it doesn't change theme - just font is getting white as it should be but there is no dark background.
I tried checking if it at least works and changed Theme.NoBarBlack in values (for android <3.0) and its value the same as Theme.NoBar and then when I pressed button font wasn't changed -as it should do.
EDIT (PROBLEM FOUND):
So after trying it turn out that on Android 2.2 Manifest file set Background and rest, and programmatically changing theme affect only text color. any idea why that happens?
ANSWER (as I don't have 10 reputation):
On android <3.0 it matters if
super.onCreate(savedInstanceState);
Is before setting up theme or not.
So it should be:
public void onCreate(Bundle savedInstanceState) {
setTheme(R.style.Theme_NoBar);
super.onCreate(savedInstanceState);
setContentView(R.layout.lista);
}
Sorry guys for making problem out of nothing but as it was working on >3.0 I was confused. Spend half of day on it but working. :)
There's a mistake in your styles.xml:
for Theme.NoBarBlack, you set the parent to #android:style/Theme.NoActionBar, but it doesn't exist.
I think you mean #android:style:Theme.NoTitleBar.

Categories

Resources