So am trying to change the colour of the header of my DatePicker. It doesn't appear to as easy as first though. You can do it in the XML like so:
android:headerBackground="#color/myColor" />
However there doesn't seem to be a way to be able to do this in code. The usual setters don't seem to be apparent (i.e datePicker.setHeaderBackground).
Any ideas?
Create custom datepicker dialog. See this link once.
You can use setAccentColor() for change color of header in this sample. use it like dpd.setAccentColor(Color.BLUE);.
If you don't want this color to buttons, just remove below lines from 'DatePickerDialog' class.
okButton.setTextColor(mAccentColor);
cancelButton.setTextColor(mAccentColor);
Here is the method to change header background of DatePickerDialog:
private void setDatePickerHeaderBackgroundColor(DatePickerDialog dpd, int color) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
try {
Field mDatePickerField;
mDatePickerField = DatePickerDialog.class.getDeclaredField("mDatePicker");
mDatePickerField.setAccessible(true);
final DatePicker mDatePicker = (DatePicker) mDatePickerField.get(dpd);
int headerId = Resources.getSystem().getIdentifier("day_picker_selector_layout", "id", "android");
final View header = mDatePicker.findViewById(headerId);
header.setBackgroundColor(color);
} catch (NoSuchFieldException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
}
}
}
As you can see I'm using java reflection for Lollipop and above to get header view.
Usage:
DatePickerDialog dpd = new DatePickerDialog(this, this, 2016, 0, 11);
setDatePickerHeaderBackgroundColor(dpd, getResources().getColor(android.R.color.black));
dpd.show();
As a result we have:
EDIT:
In case you just want to set header background of DatePicker, that you've created in xml, forgot about java reflection, just use these lines to get it working:
DatePicker mDatePicker = (DatePicker) findViewById(R.id.date_picker);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
int headerId = Resources.getSystem().getIdentifier("day_picker_selector_layout", "id", "android");
final View header = mDatePicker.findViewById(headerId);
header.setBackgroundColor(getResources().getColor(android.R.color.black));
}
create this style :
<style name="MyDatePickerStyle" parent="#android:style/Widget.Material.Light.DatePicker">
<item name="android:headerBackground">#color/chosen_header_bg_color</item>
</style
and add this style to your dialog theme :
<style name="MyDatePickerDialogTheme" parent="android:Theme.Material.Light.Dialog">
<item name="android:datePickerStyle">#style/MyDatePickerStyle</item>
</style>
and add this dialog to your app theme :
<style name="MyDatePickerStyle" parent="#android:style/Widget.Material.Light.DatePicker">
<item name="android:headerBackground">#color/chosen_header_bg_color</item>
</style>
it is very wll explained here : Change Datepicker dialog color for Android 5.0
and this did work for me.
You need to override your DatePickerStyle, follow the steps,
1) Override DatePickerDialogTheme inside your app's base theme:
<style name="AppBaseTheme" parent="android:Theme.Material.Light">
....
<item name="android:datePickerDialogTheme">#style/CustomDatePickerDialogTheme</item>
</style>
2) Define CustomDatePickerDialogTheme
<style name="CustomDatePickerDialogTheme" parent="android:Theme.Material.Light.Dialog">
<item name="android:datePickerStyle">#style/CustomDatePickerStyle</item>
</style>
3) Overridden DatePickerStyle with the style CustomDatePickerStyle
<style name="CustomDatePickerStyle" parent="#android:style/Widget.Material.Light.DatePicker">
<item name="android:headerBackground">#color/header_bg_color</item>
</style>
Hope it helps.
Edit: Sorry for missing out the code part,
Use this style to create DatePickerDialog like this:
new DatePickerDialog(getActivity(),R.style.CustomDatePickerStyle, this, year, month, day);
Related
I want to make a fully transparent status bar and navigation bar like Google Play did. When I use window settings to achieve it, the keyboard covers EditText.
When this code used EditText covered by Keyboard Input:
getWindow().setFlags(WindowManager.LayoutParams.FLAG_LAYOUT_NO_LIMITS,
WindowManager.LayoutParams.FLAG_LAYOUT_NO_LIMITS);
Also this code doesn't make it fully transparent, it just makes it translucent
getWindow().setNavigationBarColor(Color.TRANSPARENT)
or this
<item name="android:navigationBarColor">#android:color/transparent</item>
I need a window like this:
What you need is something like this:
class Utils {
static void enableInmersiveMode(Activity act, boolean drawBehindNavBar) {
View rootView = act.getWindow().getDecorView().getRootView();
int uiFlags = rootView.getSystemUiVisibility();
int flags =0;
if(drawBehindNavBar) { flags = View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION; }
flags = flags | uiFlags | View.SYSTEM_UI_FLAG_LAYOUT_STABLE | View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEEN;
rootView.setSystemUiVisibility(flags);
}
}
And in your onCreate of your activity:
#Override
void onCreate(Bundle b) {
Utils.enableInmersiveMode(this, true);
super.onCreate(b);
// setContentView and the rest of your code here...
}
Take in mind that afterwards views will go behind the system UI and you'll need to dynamically add padding to the first and last Views so the user can interact with them.
Hopefully, you can try this in your-main-path/res/values/styles.xml
This is for transparent Status Bar and Navigation Bar in any android devices.
<item name="android:statusBarColor">#android:color/transparent</item>
<item name="android:navigationBarColor">#android:color/transparent</item>
One more thing if you want to try transparency and float the to the bar you can use this but the background of Navigation Bar will reduce 50% of transparency.
<item name="android:windowTranslucentNavigation">true</item>
When you want to unset the TranslucentNavigation float, this one can fit the screen between Status Bar and Navigation Bar
<item name="android:fitsSystemWindows">true</item>
Like the title, I am wondering how to get rid of the green bar at the top so that it matches the background of the activity. I have no idea where to look I've had a look in the manifest and haven't found anything.
What do I do so that it matches the background of the activity?
Note. Different activities have different backgrounds, so is there a way that I just match the activity it is on?
The green bar is called Status bar, and to hide it in activity call below method in onCreate()
void hideStatusBar() {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) {
int uiOptions = View.SYSTEM_UI_FLAG_FULLSCREEN;
getWindow().getDecorView().setSystemUiVisibility(uiOptions);
} else {
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
}
}
And to hide it in a fragment, call it in onCreateView()
void hideStatusBar() {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) {
int uiOptions = View.SYSTEM_UI_FLAG_FULLSCREEN;
requireActivity().getWindow().getDecorView().setSystemUiVisibility(uiOptions);
} else {
requireActivity().getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
}
}
You can change status bar color using this extension function, call this function from Activity just passing the color
fun AppCompatActivity.changeStatusBarColor(#ColorRes color: Int) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
window.statusBarColor = ContextCompat.getColor(this, color)
}
}
go to following path:
app->res->values->styles
and here in style tag three item tags are available, in that colour of first and last item keep same.
then app status bar and action bar colour display same.
Example:
<!-- Base application theme. -->
<style name="AppTheme" parent="Theme.AppCompat.Light.DarkActionBar">
<!-- Customize your theme here.
<item name="colorPrimary">#color/colorPrimary</item>
<item name="colorPrimaryDark">#color/colorPrimaryDark</item>
<item name="colorAccent">#color/colorAccent</item>
-->
<item name="colorPrimary">#FFA500</item>
<item name="colorPrimaryDark">#FFA500</item>
</style>
How do I make a ChipGroup to act like a radioButton where one item can be selected at a time while changing the background color.
I saw this link for something like this but it did not help me since because am using a layoutInflater to show my chip item.
firebaseFirestore.collection("Categories").addSnapshotListener((queryDocumentSnapshots, e) -> {
for (DocumentChange doc: queryDocumentSnapshots.getDocumentChanges()){
if (doc.getType() == DocumentChange.Type.ADDED){
Categories categories = doc.getDocument().toObject(Categories.class);
post_list.add(categories);
Chip chip = (Chip) getLayoutInflater().inflate(R.layout.chip_item_layout, chipGroup, false);
chip.setText(categories.getTitle());
chipGroup.addView(chip);
chipGroup.setOnCheckedChangeListener((chipGroup, id) -> {
Chip chip2 = ((Chip) chipGroup.getChildAt(chipGroup.getCheckedChipId()));
if (chip2 != null) {
for (int i = 0; i < chipGroup.getChildCount(); ++i) {
chipGroup.getChildAt(i).setClickable(true);
chip2.setChipBackgroundColorResource(R.color.customOrange);
}
chip2.setClickable(false);
}
});
}
}
});
In your ChipGroup use the app:singleSelection="true" attribute. In this way the ChipGroup can be configured to only allow a single chip to be checked at a time.
<com.google.android.material.chip.ChipGroup
app:singleSelection="true"
..>
Then you can set a selector color using the app:chipBackgroundColor attribute in your layout chip_item_layout.xml.
Something like:
<com.google.android.material.chip.Chip
style="#style/Widget.MaterialComponents.Chip.Choice"
app:chipBackgroundColor="#color/chip_background_color"
..>
Pay attention to style="#style/Widget.MaterialComponents.Chip.Choice" because it defines the chip as android:checkable="true".
The chip_background_color is a selector where you can define your favorite colors in the different states. It is the default selector, you can change it:
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<!-- 24% opacity -->
<item android:alpha="0.24" android:color="?attr/colorPrimary" android:state_enabled="true" android:state_selected="true"/>
<item android:alpha="0.24" android:color="?attr/colorPrimary" android:state_enabled="true" android:state_checked="true"/>
<!-- 12% of 87% opacity -->
<item android:alpha="0.10" android:color="?attr/colorOnSurface" android:state_enabled="true"/>
<item android:alpha="0.12" android:color="?attr/colorOnSurface"/>
</selector>
The selected chip is define by the color in your case is the first line (android:state_selected="true").
If you would like to do it programmatically just use (not in the OnCheckedChangeListener) the setChipBackgroundColorResource method.
chip.setChipBackgroundColorResource(R.color.chip_background_color);
Also if you want to require at least one selection you can use the app:selectionRequired attribute. This attribute requires the 1.2.0 (starting from 1.2.0-alpha02)
I'm currently making a registration form, and one of the fields is for the users Date of Birth. I want to use datepicker, however I don't want the calendar layout as shown below:
I want the layout to look something like this so that way its easier to choose the year and month without having to scroll through everything:
However I do not know how to go about this, or what to put inside the styles.xml file. Any help would be greatly appreciated.
Add this to style.xml
<style name="date_picker_theme" parent="#android:style/Widget.DatePicker">
And then you should apply style for your date picker like this:
<DatePicker
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/datePicker"
style="#style/date_picker_theme" />
Create style with
<style name="DatePicker" parent="#android:style/Theme.Holo.Light">
<item name="android:datePickerStyle">#android:style/Widget.DatePicker</item>
</style>
Then in custom fragment dialog xml
<DatePicker
android:theme="#style/DatePicker"
android:id="#+id/fragment_date_picker_control"
android:datePickerMode="spinner"
android:spinnersShown="true"
android:calendarViewShown="false"
android:layout_marginLeft="#dimen/margin_normal"
android:layout_marginRight="#dimen/margin_normal"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center_horizontal" />
Link : http://yogeshkalwar.blogspot.in/2017/08/custom-spinner-datepicker-supporting-n70.html
To set the DatePicker style globally, add the following to style.xml, or adjust existing content:
<resources>
<style name="AppTheme" parent="#style/Theme.AppCompat.Light">
<item name="android:datePickerStyle">#style/MyDatePicker</item>
</style>
...
</resources>
And define your customized DatePicker style, either in style.xml or a separate file, e.g.:
<resources>
<style name="MyDatePicker" parent="#android:style/Widget.DatePicker">
<item name="android:calendarViewShown">false</item>
<item name="android:datePickerMode">spinner</item>
</style>
</resources>
It might be too late but you can set it programmatically like these.
Apply it inside your onClick listener.
DatePickerDialog datePicker = new DatePickerDialog(
this,
android.R.style.Theme_Holo_Light_Dialog_MinWidth,
datePickerListener,
cal.get(Calendar.YEAR),
cal.get(Calendar.MONTH),
cal.get(Calendar.DAY_OF_MONTH));
datePicker.setCancelable(false);
datePicker.setTitle("Select the date");
datePicker.show();
The android.R.style.Theme_Holo_Light_Dialog_MinWidth create style that you want.
Hope it helps someone.
Above properties are of XML, if you want to set it programmatically you can you the below code but I haven't checked this code whether its working or not.
datepickerDialog_object.getDatePicker().setSpinnersShown(true);
datepickerDialog_object.getDatePicker().setCalendarViewShown(false);
DatePickerDialog has a convenience method, where you set the desired layout.
public DatePickerDialog(#NonNull Context context, #StyleRes int themeResId,
#Nullable OnDateSetListener listener, int year, int monthOfYear, int dayOfMonth) {
this(context, themeResId, listener, null, year, monthOfYear, dayOfMonth);
}
public static final int MODE_SPINNER = 1;
public static final int MODE_CALENDAR = 2;
Passing 1 or 2 in themesResId does the trick.
hi try this a simplest way...
public void datePicker(final Context context, final EditText editText, final String type) {
Calendar calendar = Calendar.getInstance();
final SimpleDateFormat dateFormatter = new SimpleDateFormat("yyyy-MM-dd", Locale.US);
DatePickerDialog datePickerDialog = new DatePickerDialog(context, R.style.DialogTheme, new DatePickerDialog.OnDateSetListener() {
public void onDateSet(android.widget.DatePicker view, int year, int monthOfYear, int dayOfMonth) {
Calendar newDate = Calendar.getInstance();
newDate.set(year, monthOfYear, dayOfMonth);
newDate.set(year, monthOfYear, dayOfMonth);
editText.setText(dateFormatter.format(newDate.getTime())
}
}, calendar.get(Calendar.YEAR), calendar.get(Calendar.MONTH), calendar.get(Calendar.DAY_OF_MONTH));
// datePickerDialog.getDatePicker().setMinDate(System.currentTimeMillis() - 1000);
datePickerDialog.show();
}
android in style.xml add below line
<style name="DialogTheme" parent="Theme.AppCompat.Light.Dialog">
<item name="colorAccent">#color/AppDarkBlue</item>
</style>
Question
How does one programatically (without touching the AndroidManifext.xml) set the theme of an Activity so that it looks like a dialog?
Note: I am ok with modifying the AndroidManifext.xml as long as it does not need to be modified in order to switch between making it look like a normal activity or a dialog.
What I've tried so far
I tried the following as per this stackoverflow answer:
public class DialogActivity extends Activity
{
#Override
protected void onCreate(Bundle savedInstanceState)
{
setTheme(android.R.style.Theme_DeviceDefault_Dialog);
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_dialog);
Log.d(TAG,"Build.VERSION.SDK_INT: "+Build.VERSION.SDK_INT); // 23
}
}
But it ends up blacking out everything in the background.
I also saw this stackoverflow answer, and tried:
public class DialogActivity extends Activity
{
#Override
protected void onCreate(Bundle savedInstanceState)
{
setTheme(android.R.style.Theme_DeviceDefault_Dialog);
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_dialog);
getWindow().setBackgroundDrawable(new ColorDrawable(android.graphics.Color.TRANSPARENT));
}
}
but it ends up making everything black.
What do? Thank you.
Background
The Activity behind an Acivity is drawn if the foreground activity's theme according to its AndroidManifest.xml is a dialog; otherwise the android os will not draw the Activity behind it (probably to save memory since it usually won't be seen anyway).
To exploit this, we set the theme of our Acitvity to a dialog in the manifest, making the android os draw the Activity behind it, but later, programatically set our Activity's theme to whatever we like at runtime.
Example on github
I made an example and put it on github.
Tutorial
Step 1: create two custom themes for your application in styles.xml. One for normal activities, and another for dialog activities. It is important for the custom dialog theme to inherit from a base theme that is also a dialog. In my case, the parent theme is Base.Theme.AppCompat.Light.Dialog.FixedSize). Here is my styles.xml:
<resources>
<!-- custom normal activity theme -->
<style name="AppTheme" parent="Theme.AppCompat.Light.NoActionBar">
</style>
<!-- custom dialog activity theme -->
<style name="AppTheme.Dialog" parent="Base.Theme.AppCompat.Light.Dialog.FixedSize">
<!-- removing the dialog's action bar -->
<item name="windowActionBar">false</item>
<item name="windowNoTitle">true</item>
</style>
</resources>
Step 2: in the AndroidManifest.xml, set the theme of the Activity in question to any dialog theme. This makes the android os think that the Activity is a dialog, so it will draw the Activity behind it, and not black it out. In my case, I used Theme.AppCompat.Dialog. Below is my AndroidManifest.xml:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.eric.questiondialog_artifact">
<application
android:allowBackup="true"
android:icon="#mipmap/ic_launcher"
android:label="#string/app_name">
<activity
android:name=".DialogActivity"
android:label="#string/app_name"
android:theme="#style/Theme.AppCompat.Dialog"> <-- IMPORTANT!!! -->
<intent-filter>
<action android:name="android.intent.action.MAIN"/>
<category android:name="android.intent.category.LAUNCHER"/>
</intent-filter>
</activity>
</application>
</manifest>
Step 3: in the actual activity, set the theme programatically to either the theme for normal activities, or the theme for dialogs. My DialogActivity.java is below:
package com.example.eric.questiondialog_artifact;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
public class DialogActivity extends AppCompatActivity
{
#Override
protected void onCreate(Bundle savedInstanceState)
{
setTheme(R.style.AppTheme_Dialog); // can either use R.style.AppTheme_Dialog or R.style.AppTheme as deined in styles.xml
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_dialog);
}
}
if what you're looking for is just a theme with transparent background for you activity, just use this:
<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>
apply this style to your activity in your AndroidManifest file and this is it
I am late but still for future users
you need to call the below code after setTheme() Calling this allows the Activity behind this one to be seen again. Once all such Activities have been redrawn
// setTheme()
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
try {
Method getActivityOptions = Activity.class.getDeclaredMethod("getActivityOptions");
getActivityOptions.setAccessible(true);
Object options = getActivityOptions.invoke(activity);
Class<?>[] classes = Activity.class.getDeclaredClasses();
Class<?> translucentConversionListenerClazz = null;
for (Class clazz : classes) {
if (clazz.getSimpleName().contains("TranslucentConversionListener")) {
translucentConversionListenerClazz = clazz;
}
}
Method convertToTranslucent = Activity.class.getDeclaredMethod("convertToTranslucent",
translucentConversionListenerClazz, ActivityOptions.class);
convertToTranslucent.setAccessible(true);
convertToTranslucent.invoke(activity, null, options);
} catch (Throwable t) {
}
} else {
try {
Class<?>[] classes = Activity.class.getDeclaredClasses();
Class<?> translucentConversionListenerClazz = null;
for (Class clazz : classes) {
if (clazz.getSimpleName().contains("TranslucentConversionListener")) {
translucentConversionListenerClazz = clazz;
}
}
Method method = Activity.class.getDeclaredMethod("convertToTranslucent",
translucentConversionListenerClazz);
method.setAccessible(true);
method.invoke(activity, new Object[] {
null
});
} catch (Throwable t) {
}
}
Try these code before dailog.setMessage(...);
Dialog id = new AlertDialog.Builder(this,AlertDialog.THEME_DEVICE_DEFAULT_DARK);
Dialog ID = new AlertDialog.Builder(this,AlertDialog.THEME_DEVICE_DEFAULT_LIGHT);
//Default theme
Try this for Old theme
Dialog ID = new AlertDialog.Builder(this,AlertDialog.THEME_TRADITIONAL);
Try these for KITKAT theme
Dialog ID = new AlertDialog.Builder(this,AlertDialog.THEME_DEVICE_DEFAULT_DARK); //Dark
Dialog ID = new AlertDialog.Builder(this,AlertDialog.THEME_HOLO_LIGHT);
Try these codes for Pragmatically
Exmaple
dialog = new AlertDialog.Builder(this);
dialog = new AlertDialog.Builder(this,AlertDialog.THEME_DEVICE_DEFAULT_DARK);
dialog.setTitle("HAI");
dialog.setMessage("look");
dialog.setPositiveButton("Ok", new DialogInterface.OnClickListener() {
Toast toast= Toast.makeText(getApplicationContext(), "This is exmaple theme", Toast.LENGTH_LONG);