Setting a custom share icon on Actionbar ShareActionProvider without ActionBarSherlock - android

I have the same problem as was described here - Setting a custom share icon on Actionbar ShareActionProvider
But I'am not using ActionBarSherlockI found that the Sherlock theme uses the "actionModeShareDrawable" and I can also use it like this, if I don't use ActionBarSherlock
<style name="Theme.MyApp" parent="android:Theme.Holo">
<item name="*android:actionModeShareDrawable">#drawable/icon</item>
</style>
This works fine on my nexus 5, but failed on many other devices
So my question is, how to change that icon without using ActionBarSherlock

You can subclass ShareActionProvider, overriding only the constructor and createActionView().
From here, you can get the View from super, casting it to ActivityChooserView so you can call
setExpandActivityOverflowButtonDrawable(Drawable) to change the icon.
package com.yourpackagename.whatever;
import android.content.Context;
import android.graphics.drawable.Drawable;
import android.support.v7.internal.widget.ActivityChooserView;
import android.support.v7.widget.ShareActionProvider;
import android.view.View;
import com.yourpackagename.R;
public class CustomShareActionProvider extends ShareActionProvider {
private final Context mContext;
public CustomShareActionProvider(Context context) {
super(context);
mContext = context;
}
#Override
public View onCreateActionView() {
ActivityChooserView chooserView =
(ActivityChooserView) super.onCreateActionView();
// Set your drawable here
Drawable icon =
mContext.getResources().getDrawable(R.drawable.ic_action_share);
chooserView.setExpandActivityOverflowButtonDrawable(icon);
return chooserView;
}
}

I like PrplRugby's answer, but you have to include the ActivityChooserView in your app. I refactored to use reflection which you can find here: https://gist.github.com/briangriffey/11185716

You can use in the menu like this
menu.xml
<item android:id="#+id/menu_share"
android:title="#string/share"
app:actionProviderClass="android.support.v7.widget.ShareActionProvider"
app:showAsAction="always"
android:orderInCategory="100"/>
And into your set icon if api>21 android:actionModeShareDrawable otherwise actionModeShareDrawable
Style.xml
<!-- Base application theme. -->
<style name="AppTheme" parent="Theme.AppCompat.Light.NoActionBar">
....
<item name="actionModeShareDrawable">#drawable/share</item>
</style>
In the last apply this theme
manifest.xml
<application
...
android:theme="#style/AppTheme" >

I know this is not in a theme but I set my share icon in menu.xml. This may help if you are just trying to have a custom icon.
<menu xmlns:android="http://schemas.android.com/apk/res/android" >
<item android:id="#+id/share" android:showAsAction="always" android:title="#string/share" android:icon="#drawable/ic_menu_share"/>
</menu>
I am surprised it works at all. Try changing actionModeShareDrawalbe to actionModeShareDrawable.
<style name="Theme.MyApp" parent="android:Theme.Holo">
<item name="android:actionModeShareDrawable">#drawable/icon</item>
</style>

Related

Android App's Toolbar Title is Not Centred Vertically

I have been following the official documentation on how to create an app toolbar. The tutorial says that, after following the instructions,
"Your app now has a basic action bar. By default, the action bar
contains just the name of the app and an overflow menu."
Well, mine doesn't, it looks like this:
As you can see from this image, I've done some styling to get the colours as I want them, and I've added a menu item, just to see if it appeared correctly. I'll work out how to fix the colour of the icon later.
My problem is that, as you can see, the app title isn't centred vertically. It's too close to the top. This irritates me because, as far as I can tell, it should be centered automatically and I don't know why mine isn't, but I've nevertheless tried to fix this myself using styles, with absolutely no success. No style attributes seem to have any effect on the padding of just the Toolbar Title. I can add padding to the whole Toolbar, but that affects the menu item too, and I don't want it to.
My implementation looks like this:
activity_main.xml:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:id="#+id/activity_main"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:fitsSystemWindows="true">
<android.support.v7.widget.Toolbar
android:id="#+id/main_activity_toolbar"
android:layout_width="match_parent"
android:layout_height="?attr/actionBarSize"
style="#style/MyToolbarStyle"
app:theme="#style/MyToolbarTheme" />
</LinearLayout>
styles.xml:
<resources>
<!-- Base application theme. -->
<style name="MyTheme" parent="Theme.AppCompat.Light.NoActionBar">
<item name="colorPrimary">#color/colorPrimary</item>
<item name="colorPrimaryDark">#color/colorPrimaryDark</item>
<item name="colorAccent">#color/colorAccent</item>
</style>
<style name="MyToolbarStyle" parent="Base.Widget.AppCompat.Toolbar">
<item name="android:elevation">4dp</item>
<item name="android:background">#color/colorPrimary</item>
</style>
<style name="MyToolbarTheme" parent="Base.Widget.AppCompat.Toolbar">
<item name="android:textColorPrimary">#ffffff</item>
</style>
Ideally, if somebody could explain where I've gone wrong so that my application title isn't centered vertically, that'd be great, but if not, can somebody tell me how to add a margin or padding just to the application title in the toolbar so that I can attempt to centre it myself?
P.S. This isn't a duplicate of this question - that question deals with a more complex custom Toolbar. Mine is supposed to be the default implementation.
Update:
As requested, here's the code for my MainActivity.java file:
package com.example.samplescanner;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.Menu;
import android.view.MenuInflater;
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar MainActivityToolbar = (Toolbar) findViewById(R.id.main_activity_toolbar);
setSupportActionBar(MainActivityToolbar);
}
#Override
public boolean onCreateOptionsMenu(Menu menu)
{
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.menu_items, menu);
return super.onCreateOptionsMenu(menu);
}
}
I couldn't find the exact source of the issue from Base.Widget.AppCompat.Toolbar, but it alters the Gravity of the Toolbar. Inherit from ThemeOverlay.AppCompat.Dark.ActionBar instead:
<style name="MyTheme.ToolbarOverlay" parent="ThemeOverlay.AppCompat.Dark.ActionBar">
<item name="android:background">#color/colorPrimary</item>
<item name="android:elevation">4dp</item>
</style>
They use ThemeOverlay.AppCompat.ActionBar in the documentation you mentioned, but the Dark version should set the textColorPrimary attribute for you.

Change Text for loading screen in ActionBar-PullToRefresh library

I have successfully implemented ActionBar-PullToRefresh in my code. Now whenever I refresh the list it shows "Loading ..." text in ActionBar.
So how to change that text in ActionBar. Do I directly change the string in the library or is there any other way to do that...
Approved approach from the samples
Source: https://github.com/chrisbanes/ActionBar-PullToRefresh/tree/master/samples
Create a theme with text overrides (e.g. ptrPullText),
that is, res/values/styles.xml:
<resources>
<style name="Theme.Holo.CustomPtrHeader" parent="android:Theme.Holo">
<item name="ptrHeaderStyle">#style/Widget.Custom.PtrHeader</item>
</style>
<style name="Widget.Custom.PtrHeader" parent="android:Widget">
<item name="ptrRefreshingText">Pulling down the internet</item>
</style>
</resources>
Apply the custom theme to your activity in AndroidManifest.xml
<activity
...
android:theme="#style/Theme.Holo.CustomPtrHeader" />
or Register you own HeaderTransformer
For the example on how to do this, please see the GridView sample.
or A little hackier way
Please note that setPullText is not on the HeaderTransformer interface, it's an instance method of DefaultHeaderTransformer:
attacher = PullToRefreshAttacher.get(this);
attacher.addRefreshableView(listView, this);
transformer = ((DefaultHeaderTransformer)attacher.getHeaderTransformer());
transformer.setRefreshingText("Pulling down the internet");

ActionBarCompat: java.lang.IllegalStateException: You need to use a Theme.AppCompat

I am getting a RuntimeException on Android 2.3.5 but I am using Theme.AppCompat (res/values/themes.xml). This is the phone: http://www.gsmarena.com/samsung_galaxy_y_s5360-4117.php
<!-- res/values/themes.xml -->
<?xml version="1.0" encoding="utf-8"?>
<resources>
<style name="Theme.Styled" parent="#style/Theme.AppCompat">
<item name="actionBarStyle">#style/QueryActionBar</item>
<item name="android:actionBarStyle">#style/QueryActionBar</item>
</style>
<style name="QueryActionBar" parent="#style/Widget.AppCompat.ActionBar">
<item name="background">#color/blueback</item>
<item name="android:background">#color/blueback</item>
<item name="backgroundSplit">#color/blueback</item>
<item name="android:backgroundSplit">#color/blueback</item>
</style>
</resources>
Here is the file for values-v11.
<!-- res/values-v11/themes.xml -->
<?xml version="1.0" encoding="utf-8"?>
<resources>
<style name="QueryTheme" parent="#android:style/Theme.Holo">
<!-- Any customizations for your app running on devices with Theme.Holo here -->
</style>
</resources>
Here is the error.
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.txt2lrn.www/com.txt2lrn.www.LandingActivity}: java.lang.IllegalStateException: You need to use a Theme.AppCompat theme (or descendant) with this activity.
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1651)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:1667)
at android.app.ActivityThread.access$1500(ActivityThread.java:117)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:935)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:130)
at android.app.ActivityThread.main(ActivityThread.java:3687)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:507)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:867)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:625)
at dalvik.system.NativeStart.main(Native Method)
Caused by: java.lang.IllegalStateException: You need to use a Theme.AppCompat theme (or descendant) with this activity.
at android.support.v7.app.ActionBarActivityDelegate.onCreate(ActionBarActivityDelegate.java:102)
at android.support.v7.app.ActionBarActivity.onCreate(ActionBarActivity.java:98)
at com.txt2lrn.www.LandingActivity.onCreate(LandingActivity.java:95)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1047)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1615)
... 11 more
Sorry folks, I also do have android:theme="#style/Theme.Styled" defined in AndroidManifest.xml.
If you are extending ActionBarActivity in your MainActivity, you will have to change the parent theme in values-v11 also.
So the style.xml in values-v11 will be -
<!-- res/values-v11/themes.xml -->
<?xml version="1.0" encoding="utf-8"?>
<resources>
<style name="QueryTheme" parent="#style/Theme.AppCompat">
<!-- Any customizations for your app running on devices with Theme.Holo here -->
</style>
</resources>
EDIT: I would recommend you stop using ActionBar and start using the AppBar layout included in the Android Design Support Library
To simply add ActionBar Compat your activity or application should use #style/Theme.AppCompat theme in AndroidManifest.xml like this:
<activity
...
android:theme="#style/Theme.AppCompat" />
This will add actionbar in activty(or all activities if you added this theme to application)
But usually you need to customize you actionbar. To do this you need to create two styles with Theme.AppCompat parent, for example, "#style/Theme.AppCompat.Light". First one will be for api 11>= (versions of android with build in android actionbar), second one for api 7-10 (no build in actionbar).
Let's look at first style. It will be located in res/values-v11/styles.xml . It will look like this:
<style name="Theme.Styled" parent="#style/Theme.AppCompat.Light">
<!-- Setting values in the android namespace affects API levels 11+ -->
<item name="android:actionBarStyle">#style/Widget.Styled.ActionBar</item>
</style>
<style name="Widget.Styled.ActionBar" parent="#style/Widget.AppCompat.Light.ActionBar">
<!-- Setting values in the android namespace affects API levels 11+ -->
<item name="android:background">#drawable/ab_custom_solid_styled</item>
<item name="android:backgroundStacked"
>#drawable/ab_custom_stacked_solid_styled</item>
<item name="android:backgroundSplit"
>#drawable/ab_custom_bottom_solid_styled</item>
</style>
And you need to have same style for api 7-10. It will be located in res/values/styles.xml, BUT because that api levels don't yet know about original android actionbar style items, we should use one, provided by support library. ActionBar Compat items are defined just like original android, but without "android:" part in the front:
<style name="Theme.Styled" parent="#style/Theme.AppCompat.Light">
<!-- Setting values in the default namespace affects API levels 7-11 -->
<item name="actionBarStyle">#style/Widget.Styled.ActionBar</item>
</style>
<style name="Widget.Styled.ActionBar" parent="#style/Widget.AppCompat.Light.ActionBar">
<!-- Setting values in the default namespace affects API levels 7-11 -->
<item name="background">#drawable/ab_custom_solid_styled</item>
<item name="backgroundStacked">#drawable/ab_custom_stacked_solid_styled</item>
<item name="backgroundSplit">#drawable/ab_custom_bottom_solid_styled</item>
</style>
Please mark that, even if api levels higher than 10 already have actionbar you should still use AppCompat styles. If you don't, you will have this error on launch of Acitvity on devices with android 3.0 and higher:
java.lang.IllegalStateException: You need to use a Theme.AppCompat
theme (or descendant) with this activity.
Here is link this original article http://android-developers.blogspot.com/2013/08/actionbarcompat-and-io-2013-app-source.html written by Chris Banes.
Check and make sure that you do not have another values folder that references theme.styled and does not use AppCompat theme
ie values-v11 folder
Try this...
styles.xml
<resources>
<style name="Theme.AppCompat.Light.NoActionBar" parent="#style/Theme.AppCompat.Light">
<item name="android:windowNoTitle">true</item>
</style>
</resources>
AndroidManifest.xml
<activity
android:name="com.example.Home"
android:label="#string/app_name"
android:theme="#style/Theme.AppCompat.Light.NoActionBar"
>
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
Your Activity is extending ActionBarActivity which requires the AppCompat.theme to be applied.
Change from ActionBarActivity to Activity or FragmentActivity, it will solve the problem.
Just do it Build -> Clean Project. I think this will solve your problem.
My manifest does not reference any themes... it should not have to AFAIK
Sure it does. Nothing is going to magically apply Theme.Styled to an activity. You need to declare your activities -- or your whole application -- is using Theme.Styled, e.g., :
<application
android:icon="#drawable/ic_launcher"
android:label="#string/app_name"
android:theme="#style/Theme.Styled">
I had such crash on Samsung devices even though the activity did use Theme.AppCompat.
The root cause was related to weird optimizations on Samsung side:
- if one activity of your app has theme not inherited from Theme.AppCompat
- and it has also `android:launchMode="singleTask"`
- then all the activities that are launched from it will share the same Theme
My solution was just removing android:launchMode="singleTask"
I encountered this error when I was trying to create a DialogBox when some action is taken inside the CustomAdapter class.
This was not an Activity but an Adapter class.
After 36 hrs of efforts and looking up for solutions, I came up with this.
Send the Activity as a parameter while calling the CustomAdapter.
CustomAdapter ca = new CustomAdapter(MyActivity.this,getApplicationContext(),records);
Define the variables in the custom Adapter.
Activity parentActivity;
Context context;
Call the constructor like this.
public CustomAdapter(Activity parentActivity,Context context,List<Record> records){
this.parentActivity=parentActivity;
this.context=context;
this.records=records;
}
And finally when creating the dialog box inside the adapter class, do it like this.
AlertDialog ad = new AlertDialog.Builder(parentActivity).setTitle("Your title");
and so on..
I hope this helps you
I just get my application move from ActionBarSherlock to ActionBarCompat.
Try declare your old theme like this:
<style name="Theme.Event" parent="Theme.AppCompat">
Then set the theme in your AndroidManifest.xml:
<application
android:debuggable="true"
android:name=".activity.MyApplication"
android:allowBackup="true"
android:icon="#drawable/ic_launcher"
android:label="#string/app_name"
android:theme="#style/Theme.Event.Home"
>
in my case i made a custom view
i added to custom view constructor
new RoomView(getAplicationContext());
the correct context is activity so changed it to:
new RoomView(getActivity());
or
new RoomView(this);
For my list view am using custom Adapter which extends ArrayAdapter.
in listiview i have 2 buttons one of the buttons as Custom AlertDialogBox.
Ex:
Activity parentActivity;
Constructor for Adapter
`
public CustomAdapter(ArrayList<Contact> data, Activity parentActivity,Context context) {
super(context,R.layout.listdummy,data);
this.mContext = context;
this.parentActivity = parentActivity;
}
`
calling Adapter from MainActivty
adapter = new CustomAdapter(dataModels,MainActivity.this,this);
now write ur alertdialog inside ur button which is in the Adapter class
viewHolder.update.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(final View view) {
AlertDialog.Builder alertDialog = new AlertDialog.Builder(parentActivity);
alertDialog.setTitle("Updating");
alertDialog.setCancelable(false);
LayoutInflater layoutInflater = (LayoutInflater) mContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
#SuppressLint("InflateParams") final View view1 = layoutInflater.inflate(R.layout.dialog,null);
alertDialog.setView(view1);
alertDialog.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
dialogInterface.cancel();
}
});
alertDialog.setPositiveButton("Update", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
//ur logic
}
}
});
alertDialog.create().show();
}
});
para resolver o meu problema, eu apenas adicionei na minha MainActivity ("Theme = To solve my problem, I just added it in my MainActivity ("Theme =" # style / MyTheme "") where MyTheme is the name of my theme
[Activity(Label = "Name Label", MainLauncher = true, Icon = "#drawable/icon", LaunchMode = LaunchMode.SingleTop, Theme = "#style/MyTheme")]

Customizing android.widget.SearchView

Is it possible to customize layout of android.widget.SearchView (I'm using it in actionBar)?
I want to change icon and TextField background.
I've found the only one way to do that- to use reflections.
SearchView mSearchView = (SearchView)menu.findItem(R.id.search).getActionView();
try
{
Field searchField = SearchView.class.getDeclaredField("mSearchButton");
searchField.setAccessible(true);
ImageView searchBtn = (ImageView)searchField.get(mSearchView);
searchBtn.setImageResource(R.drawable.search_img);
searchField = SearchView.class.getDeclaredField("mSearchPlate");
searchField.setAccessible(true);
LinearLayout searchPlate = (LinearLayout)searchField.get(mSearchView);
((ImageView)searchPlate.getChildAt(0)).setImageResource(R.drawable.search_img);
searchPlate.setBackgroundResource(R.drawable.edit_text_bkg);
}
catch (NoSuchFieldException e)
{
Log.e(TAG,e.getMessage(),e);
}
catch (IllegalAccessException e)
{
Log.e(TAG,e.getMessage(),e);
}
If you use Appcompat v7, there is a way to do it without using reflection:
Declare the following style, and customize only those properties you need to customize, remove the rest (so they are inerhited from the parent style):
<style name="Widget.AppCompat.SearchView.CustomSearchView" parent="#style/Widget.AppCompat.SearchView">
<item name="layout">#layout/abc_search_view</item>
<item name="queryBackground">#drawable/abc_textfield_search_material</item>
<item name="submitBackground">#drawable/abc_textfield_search_material</item>
<item name="closeIcon">#drawable/abc_ic_clear_mtrl_alpha</item>
<item name="goIcon">#drawable/abc_ic_go_search_api_mtrl_alpha</item>
<item name="voiceIcon">#drawable/abc_ic_voice_search_api_mtrl_alpha</item>
<item name="commitIcon">#drawable/abc_ic_commit_search_api_mtrl_alpha</item>
<item name="suggestionRowLayout">#layout/abc_search_dropdown_item_icons_2line</item>
<item name="searchIcon">#drawable/ic_action_search</item>
</style>
Now, in your theme, use the same property:
<item name="searchViewStyle">#style/Widget.AppCompat.SearchView.Bonial</item>
Of course, your theme must inherit from one of the AppCompat themes, in my case, it was something like this:
<style name="Theme.MyActionBarActivity" parent="#style/Theme.AppCompat.Light">
Also your activities should extend ActionBarActivity and use the "support" version of the action bar methods. More info here.
I also read an article of a guy that declared the styles in some other way, but also using AppCompat v7:
http://www.jayway.com/2014/06/02/android-theming-the-actionbar/
If you are using android native SearchView and you want to change small search icon, which appears when searchView is expanded, then you are in trouble. Because attribute searchViewSearchIcon is internal, and can't be modified using styles.
Code snippet from SearchView class:
private int getSearchIconId() {
TypedValue outValue = new TypedValue();
getContext().getTheme().resolveAttribute(com.android.internal.R.attr.searchViewSearchIcon,
outValue, true);
return outValue.resourceId;
}
In ActionBarSherlock:
<style name="Your_Theme" parent="#style/Theme.Sherlock">
<item name="searchViewSearchIcon"> #drawable/ic_menu_search </item>
</style>
In Holo:
<style name="Your_Theme" parent="#style/Theme.Light">
<item name="android:searchViewSearchIcon"> #drawable/ic_search </item>
</style>

change background color of Preference

I have a PreferenceCategory, xml file and I have defined all preferences in it, I call this from class that extends PreferenceActivity. I am unable to set the background of my settings screen, this screen is displayed with help of xml file shown below. Please see that I have already defined the android:background="#041A37", still the screen remains default color: black.
public class MyPreferenceActivity extends PreferenceActivity {
#Override
public void onCreate(Bundle savedInstanceState) {
Context mContext=super.getBaseContext();
super.onCreate(savedInstanceState);
addPreferencesFromResource(R.layout.preference);
//v.setBackgroundColor(Color.rgb(4, 26, 55));
}
}
preference.xml is
<?xml version="1.0" encoding="utf-8"?>
<PreferenceScreen xmlns:android="http://schemas.android.com/apk/res/android"
android:background="#041A37" >
<PreferenceCategory>
<com.dropcall.SeekBarPreference
android:background="#041A37"
android:defaultValue="5"
android:key="#string/Interference_Delay"
android:progressDrawable="#drawable/seekbardrawable"
android:title="Seconds Delay until intereference" />
<com.dropcall.SeekBarPreference2
android:defaultValue="30"
android:key="#string/Drop_Delay"
android:progressDrawable="#drawable/seekbardrawable"
android:title="Seconds delay until drop" />
<CheckBoxPreference
android:background="#drawable/state_normal"
android:defaultValue="true"
android:key="#string/Drop_Option"
android:title="Close after call drop" />
<CheckBoxPreference
android:background="#drawable/state_normal"
android:defaultValue="true"
android:key="#string/Timer_Option"
android:title="Start timers on launch" />
</PreferenceCategory>
</PreferenceScreen>
Although I have set android:background="#041A37" in every file, the background doesn't turn into navy blue, or any other color for that matter. It remains default color, black. How to change the background color. Please let me know any pointers / hints , if you had faced same issue let me know what changes you made to set the background color.
You can define a theme and then set this for your PreferenceActivity in the manifest. Your theme can then define a a background color or a windowBackground image should you prefer that.
Manifest:
<activity android:label="#string/app_label" android:name=".client.PreferencesActivity"
android:theme="#style/PreferencesTheme">
<intent-filter>
</intent-filter>
</activity>
Then add the theme to your styles.xml
<style name="PreferencesTheme">
<item name="android:windowBackground">#drawable/background_image</item>
<item name="android:background">#FFEAEAEA</item>
</style>
In the above snippet there's both a background color and a background image defined to show how to do it.
This worked for me
getListView().setBackgroundColor(Color.TRANSPARENT);
getListView().setCacheColorHint(Color.TRANSPARENT);
getListView().setBackgroundColor(Color.rgb(4, 26, 55));
Another work-around as far as color goes is that you create a theme for the preferences activity and put the background color of list views as well:
<style name="PrefsTheme" parent="#android:style/Theme.Black.NoTitleBar">
<item name="android:windowBackground">#color/prefs_bg</item>
<item name="android:textColor">#color/text_color</item>
<item name="android:listViewStyle">#style/listViewPrefs</item>
</style>
<style name="listViewPrefs" parent="#android:style/Widget.ListView">
<item name="android:background">#color/prefs_bg</item>
<item name="android:cacheColorHint">#color/prefs_bg</item>
</style>
android:background is not an available attribute, according to the documentation.
It is possible you could theme the PreferenceActivity to achieve your color change, though I have not tried this, because I want my preferences to look like those of the rest of Android, to improve usability of the app.
Or you can also make drawable as your background:
getListView().setBackgroundDrawable(getResources().getDrawable(R.drawable.bluegradient));
Note: setBackgroundDrawable() is deprecated. Use setBackground() instead.
getListView().setBackground(getResources().getDrawable(R.drawable.bluegradient));
I faced with the same requirement (Androidx Preference Screen background for settings fragment).
The below code has worked for me in a fragment. (in themes.xml). I assume that it is gonna work also for an activity.
<resources xmlns:tools="http://schemas.android.com/tools">
<!-- Base application theme. -->
<style name="Theme.MyApplication" parent="Theme.MaterialComponents.DayNight.DarkActionBar">
...............
<!-- Add below -->
<item name="preferenceTheme">#style/preference</item>
</style>
<style name="preference" parent="Theme.AppCompat">
<item name="android:background">#color/purple_200</item>
</style>
</resources>
Please specify a linear layout with a textview attached and specify background color and attach this xml to preferencecategory using the layout property.
<PreferenceCategory
android:layout="#layout/preftitle"
>
Where preftitle is an xml which has a linear layout and text view attached.
Go to res>values>styles.xml> and add this code to your <style > </style>
the style should must be app base theme
in this #color/activ is color resources added to colors.
<style name="app_theme" parent="#android:style/Theme">
<item name="android:windowBackground">#color/activ</item>
<item name="android:windowContentOverlay">#drawable/title_bar_shadow</item>
<item name="android:listViewStyle">#style/TransparentListView</item>
</style>
if you use app_theme name of style tag
then add like this to your manifest
<application
android:name=".XXXXXX"
android:allowBackup="true"
android:icon="#drawable/ic_launcher"
android:label="#string/app_name"
android:theme="#style/app_theme" > //here
If you only want to change your background
I am using the PreferenceFragmentCompat, the below solution worked for me.
SettingsScreen
import android.os.Bundle
import android.util.TypedValue
import android.view.View
import androidx.annotation.ColorInt
import androidx.preference.ListPreference
import androidx.preference.Preference
import androidx.preference.PreferenceFragmentCompat
import com.almarai.easypick.R
class SettingsScreen : PreferenceFragmentCompat(),
Preference.OnPreferenceChangeListener {
override fun onCreatePreferences(savedInstanceState: Bundle?, rootKey: String?) {
//Providing the XML file for the view to be created
setPreferencesFromResource(R.xml.app_settings_preferences, rootKey)
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
//Get the Theme specific color
val typedValue = TypedValue()
val theme = requireContext().theme
/*R.attr.colorBackgroundScreenBody is my own attr from attrs.xml file,
you can directly use R.color.red - Or any color from your colors.xml
file if you do not have multi-theme app.*/
theme.resolveAttribute(R.attr.colorBackgroundScreenBody, typedValue, true)
#ColorInt val color = typedValue.data
view.setBackgroundColor(color)
super.onViewCreated(view, savedInstanceState)
}
}

Categories

Resources