Change background color of edittext in android - android

If I change the background color of my EditText using the below code, it looks like the box is shrunken and it doesn't maintain the ICS theme of a blue bottom border that exists for a default EditText.
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:background="#99000000"
>
<EditText
android:id="#+id/id_nick_name"
android:layout_marginTop="80dip"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:background="#ffffff"
/>
<LinearLayout
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_marginTop="10dip"
android:layout_marginLeft="20dip"
android:layout_marginRight="20dip"
android:orientation="horizontal"
android:layout_below="#+id/id_nick_name">
<Button
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="add"
android:layout_weight="1"
/>
<Button
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="cancel"
android:layout_weight="1"
/>
</LinearLayout>
</RelativeLayout>
Here is what it looks like:

one line of lazy code:
mEditText.getBackground().setColorFilter(Color.RED, PorterDuff.Mode.SRC_ATOP);

Here the best way
First : make new xml file in res/drawable name it rounded_edit_text then paste this:
<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
android:shape="rectangle" android:padding="10dp">
<solid android:color="#F9966B" />
<corners
android:bottomRightRadius="15dp"
android:bottomLeftRadius="15dp"
android:topLeftRadius="15dp"
android:topRightRadius="15dp" />
</shape>
Second: in res/layout copy and past following code (code of EditText)
<EditText
android:id="#+id/txtdoctor"
android:layout_width="match_parent"
android:layout_height="30dp"
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true"
android:background="#drawable/rounded_edit_text"
android:ems="10" >
<requestFocus />
</EditText>

I create color.xml file, for naming my color name (black, white...)
<?xml version="1.0" encoding="utf-8"?>
<resources>
<color name="white">#ffffff</color>
<color name="black">#000000</color>
</resources>
And in your EditText, set color
<EditText
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="asdsadasdasd"
android:textColor="#color/black"
android:background="#color/white"
/>
or use style
in you style.xml:
<style name="EditTextStyleWhite" parent="android:style/Widget.EditText">
<item name="android:textColor">#color/black</item>
<item name="android:background">#color/white</item>
</style>
and add ctreated style to EditText:
<EditText
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="asdsadasdasd"
style="#style/EditTextStyleWhite"
/>

What you should do is to create a 9 patch image for edittext and set that image as edit text background. You can create 9 patches using this website
I am attaching a sample 9 patch image for your reference.Use it as edittext background and you will get an idea.Right click the image and select "save image as". When you save the image dont forget to give its extension as "9.png"

The color you are using is white "#ffffff" is white so try a different one change in the values if you want until you get your need from this link Color Codes
and it should go fine

The simplest solution I have found is to change the background color programmatically. This does not require dealing with any 9-patch images:
((EditText) findViewById(R.id.id_nick_name)).getBackground()
.setColorFilter(Color.<your-desi‌​red-color>, PorterDuff.Mode.MULTIPLY);
Source: another answer

You should use style instead of background color. Try searching holoeverywhere then I think this one will help you solve your problem
Using holoeverywhere
just change some of the 9patch resources to customize the edittext look and feel.

For me this code it work
So put this code in XML file rounded_edit_text
<layer-list xmlns:android="http://schemas.android.com/apk/res/android" >
<item>
<shape
android:shape="rectangle">
<stroke android:width="1dp" android:color="#3498db" />
<solid android:color="#00FFFFFF" />
<padding
android:left="5dp"
android:top="5dp"
android:right="5dp"
android:bottom="5dp" >
</padding>
</shape>
</item>
</layer-list>

I worked out a working solution to this problem after 2 days of struggle, below solution is perfect for them who want to change few edit text only, change/toggle color through java code, and want to overcome the problems of different behavior on OS versions due to use setColorFilter() method.
import android.content.Context;
import android.graphics.PorterDuff;
import android.graphics.drawable.Drawable;
import android.support.v4.content.ContextCompat;
import android.support.v7.widget.AppCompatDrawableManager;
import android.support.v7.widget.AppCompatEditText;
import android.util.AttributeSet;
import com.newco.cooltv.R;
public class RqubeErrorEditText extends AppCompatEditText {
private int errorUnderlineColor;
private boolean isErrorStateEnabled;
private boolean mHasReconstructedEditTextBackground;
public RqubeErrorEditText(Context context) {
super(context);
initColors();
}
public RqubeErrorEditText(Context context, AttributeSet attrs) {
super(context, attrs);
initColors();
}
public RqubeErrorEditText(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
initColors();
}
private void initColors() {
errorUnderlineColor = R.color.et_error_color_rule;
}
public void setErrorColor() {
ensureBackgroundDrawableStateWorkaround();
getBackground().setColorFilter(AppCompatDrawableManager.getPorterDuffColorFilter(
ContextCompat.getColor(getContext(), errorUnderlineColor), PorterDuff.Mode.SRC_IN));
}
private void ensureBackgroundDrawableStateWorkaround() {
final Drawable bg = getBackground();
if (bg == null) {
return;
}
if (!mHasReconstructedEditTextBackground) {
// This is gross. There is an issue in the platform which affects container Drawables
// where the first drawable retrieved from resources will propogate any changes
// (like color filter) to all instances from the cache. We'll try to workaround it...
final Drawable newBg = bg.getConstantState().newDrawable();
//if (bg instanceof DrawableContainer) {
// // If we have a Drawable container, we can try and set it's constant state via
// // reflection from the new Drawable
// mHasReconstructedEditTextBackground =
// DrawableUtils.setContainerConstantState(
// (DrawableContainer) bg, newBg.getConstantState());
//}
if (!mHasReconstructedEditTextBackground) {
// If we reach here then we just need to set a brand new instance of the Drawable
// as the background. This has the unfortunate side-effect of wiping out any
// user set padding, but I'd hope that use of custom padding on an EditText
// is limited.
setBackgroundDrawable(newBg);
mHasReconstructedEditTextBackground = true;
}
}
}
public boolean isErrorStateEnabled() {
return isErrorStateEnabled;
}
public void setErrorState(boolean isErrorStateEnabled) {
this.isErrorStateEnabled = isErrorStateEnabled;
if (isErrorStateEnabled) {
setErrorColor();
invalidate();
} else {
getBackground().mutate().clearColorFilter();
invalidate();
}
}
}
Uses in xml
<com.rqube.ui.widget.RqubeErrorEditText
android:id="#+id/f_signup_et_referral_code"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_toEndOf="#+id/referral_iv"
android:layout_toRightOf="#+id/referral_iv"
android:ems="10"
android:hint="#string/lbl_referral_code"
android:imeOptions="actionNext"
android:inputType="textEmailAddress"
android:textSize="#dimen/text_size_sp_16"
android:theme="#style/EditTextStyle"/>
Add lines in style
<style name="EditTextStyle" parent="android:Widget.EditText">
<item name="android:textColor">#color/txt_color_change</item>
<item name="android:textColorHint">#color/et_default_color_text</item>
<item name="colorControlNormal">#color/et_default_color_rule</item>
<item name="colorControlActivated">#color/et_engagged_color_rule</item>
</style>
java code to toggle color
myRqubeEditText.setErrorState(true);
myRqubeEditText.setErrorState(false);

This is my working solution
View view = new View(getApplicationContext());
view.setBackgroundResource(R.color.background);
myEditText.setBackground(view.getBackground());

Related

How to change material designed dialog positive button background correctly

I have the following dialog
It is created by using the following code
#Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
Random random = new Random();
// 0 or 1.
final int value = random.nextInt(2);
final int title = R.string.we_love_you_0;
final int content = R.string.rate_us_with_5_stars_review_0;
final AlertDialog dialog = new AlertDialog.Builder(this.getActivity())
.setTitle(title)
.setMessage(content)
// Add action buttons
.setPositiveButton(R.string.rate_5_stars, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int id) {
}
})
.setNegativeButton(R.string.no, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
}
})
.setNeutralButton(R.string.later, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
}
})
.create();
dialog.setCanceledOnTouchOutside(false);
return dialog;
}
Since, we want to draw user attention on the positive button (RATE 5 STARS). We tend to
Have a white button text color
Have a blue button background color
We add the following code, just before returning dialog
dialog.setOnShowListener(new DialogInterface.OnShowListener() {
#Override
public void onShow(DialogInterface d) {
Button positiveButton = dialog.getButton(AlertDialog.BUTTON_POSITIVE);
positiveButton.setTextColor(rateAppDialogPositiveButtonTextColor);
positiveButton.setBackgroundColor(rateAppDialogPositiveButtonBackgroundColor);
}
});
We get the following outcome
It doesn't achieve what we want as
The positive button lost its default margin and padding information.
The positive button pressed ripple selector behavior gone.
This is how it is being compared, with normal button pressed. In our case, when we press on the positive button, no visual change.
Is there a proper way to change material designed dialog positive button background, without losing its default margin, padding and ripple selector behavior?
Create Custom dialog like this way so you can give it color.
Just a simple one! Create a dialog method, something like this anywhere in your Java class:
public void openDialog() {
final Dialog dialog = new Dialog(context); // Context, this, etc.
dialog.setContentView(R.layout.dialog_demo);
dialog.setTitle(R.string.dialog_title);
dialog.show();
}
Now create Layout XML dialog_demo.xml and create your UI/design. Here is a sample one I created for demo purposes:
<?xml version="1.0" encoding="utf-8"?>
<TextView
android:id="#+id/textview1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:padding="10dp"
android:textColor="#000000"
android:text="We love you!"
android:textStyle="bold"
android:layout_marginLeft="10dp"
android:textSize="16sp"/>
<TextView
android:id="#+id/textview2"
android:layout_below="#+id/textview1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textColor="#000000"
android:text="Can we assume that the feeling's mutual ?"
android:layout_marginLeft="20dp"
android:layout_marginRight="30dp"
android:textSize="16sp"/>
<TextView
android:id="#+id/textview3"
android:layout_below="#+id/textview2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textColor="#000000"
android:text="If you've been enjoying our app, we'd really appreciate it if you could leave us a nice revire in the market."
android:layout_marginLeft="20dp"
android:layout_marginTop="10dp"
android:layout_marginRight="30dp"
android:textSize="16sp"/>
<TextView
android:id="#+id/textview4"
android:layout_below="#+id/textview3"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textColor="#000000"
android:text="It'll really help us grow ?"
android:layout_marginLeft="20dp"
android:layout_marginRight="30dp"
android:layout_marginTop="10dp"
android:textSize="16sp"/>
<Button
android:id="#+id/dialog_later"
android:layout_width="wrap_content"
android:layout_below="#+id/textview4"
android:layout_height="wrap_content"
android:textColor="#0072BA"
android:textSize="14sp"
android:textStyle="bold"
android:layout_marginTop="10dp"
android:background="#android:color/transparent"
android:text="LATER"/>
<Button
android:id="#+id/dialog_no"
android:layout_width="wrap_content"
android:layout_below="#+id/textview4"
android:layout_height="wrap_content"
android:textColor="#0072BA"
android:textSize="14sp"
android:textStyle="bold"
android:layout_marginTop="10dp"
android:layout_marginLeft="60dp"
android:background="#android:color/transparent"
android:text="NO"/>
<Button
android:id="#+id/dialog_ratestar"
android:layout_width="wrap_content"
android:layout_below="#+id/textview4"
android:layout_height="wrap_content"
android:textColor="#FFFFFF"
android:textSize="14sp"
android:textStyle="bold"
android:layout_marginTop="10dp"
android:layout_marginLeft="100dp"
android:background="#0072BA"
android:layout_alignParentEnd="true"
android:layout_alignParentRight="true"
android:layout_marginRight="10dp"
android:padding="5dp"
android:text="RATE 5 STARS *"/>
Now you can call openDialog() from anywhere you like :) Here is the screenshot of above code.
Note that text and color are used from strings.xml and colors.xml. You can define your own.
By referring https://stackoverflow.com/a/27505229/72437, I was able to change the background of positive button, without affecting its default margin, padding and selector behavior.
Note that, we don't use colorButtonNormal, as there is no way to change the button style in Java code.
dimens.xml
<?xml version="1.0" encoding="utf-8"?>
<resources>
<!-- Default insets (outer padding) around buttons -->
<dimen name="button_inset_vertical_material">6dp</dimen>
<dimen name="button_inset_horizontal_material">#dimen/control_inset_material</dimen>
<!-- Default inner padding within buttons -->
<dimen name="button_padding_vertical_material">#dimen/control_padding_material</dimen>
<dimen name="button_padding_horizontal_material">8dp</dimen>
<!-- Default insets (outer padding) around controls -->
<dimen name="control_inset_material">4dp</dimen>
<!-- Default inner padding within controls -->
<dimen name="control_padding_material">4dp</dimen>
<!-- Default rounded corner for controls -->
<dimen name="control_corner_material">2dp</dimen>
</resources>
colors.xml
<color name="rate_app_dialog_positive_button_text_color_material_light">#ffffffff</color>
<color name="rate_app_dialog_positive_button_background_color_material_light">#ff0091ea</color>
<color name="rate_app_dialog_positive_button_pressed_background_color_material_light">#7f0091ea</color>
attrs.xml
<attr name="rateAppDialogPositiveButtonTextColor" format="color" />
<attr name="rateAppDialogPositiveButtonSelector" format="color" />
drawable-v21/rate_app_dialog_positive_button_selector_for_ripple_material_light.xml
<?xml version="1.0" encoding="utf-8"?>
<!-- Used as the canonical button shape. -->
<inset xmlns:android="http://schemas.android.com/apk/res/android"
android:insetLeft="#dimen/button_inset_horizontal_material"
android:insetTop="#dimen/button_inset_vertical_material"
android:insetRight="#dimen/button_inset_horizontal_material"
android:insetBottom="#dimen/button_inset_vertical_material">
<shape android:shape="rectangle"
android:tint="#color/rate_app_dialog_positive_button_background_color_material_light">
<corners android:radius="#dimen/control_corner_material" />
<solid android:color="#ffffffff" />
<padding android:left="#dimen/button_padding_horizontal_material"
android:top="#dimen/button_padding_vertical_material"
android:right="#dimen/button_padding_horizontal_material"
android:bottom="#dimen/button_padding_vertical_material" />
</shape>
</inset>
drawable-v21/rate_app_dialog_positive_button_selector_material_light.xml
<?xml version="1.0" encoding="utf-8"?>
<!-- https://stackoverflow.com/questions/28484369/what-should-be-the-color-of-the-ripple-colorprimary-or-coloraccent-material-d -->
<ripple xmlns:android="http://schemas.android.com/apk/res/android"
android:color="#color/ripple_material_dark">
<!-- #color/ripple_material_light -->
<!-- #color/ripple_material_dark -->
<item android:drawable="#drawable/rate_app_dialog_positive_button_selector_for_ripple_material_light" />
</ripple>
drawable/rate_app_dialog_positive_button_selector_material_light.xml
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<!-- pressed state -->
<item android:state_pressed="true">
<inset xmlns:android="http://schemas.android.com/apk/res/android"
android:insetLeft="#dimen/button_inset_horizontal_material"
android:insetTop="#dimen/button_inset_vertical_material"
android:insetRight="#dimen/button_inset_horizontal_material"
android:insetBottom="#dimen/button_inset_vertical_material">
<shape android:shape="rectangle">
<corners android:radius="#dimen/control_corner_material" />
<solid android:color="#color/rate_app_dialog_positive_button_pressed_background_color_material_light" />
<padding android:left="#dimen/button_padding_horizontal_material"
android:top="#dimen/button_padding_vertical_material"
android:right="#dimen/button_padding_horizontal_material"
android:bottom="#dimen/button_padding_vertical_material" />
</shape>
</inset>
</item>
<!-- focused state -->
<item android:state_focused="true">
<inset xmlns:android="http://schemas.android.com/apk/res/android"
android:insetLeft="#dimen/button_inset_horizontal_material"
android:insetTop="#dimen/button_inset_vertical_material"
android:insetRight="#dimen/button_inset_horizontal_material"
android:insetBottom="#dimen/button_inset_vertical_material">
<shape android:shape="rectangle">
<corners android:radius="#dimen/control_corner_material" />
<solid android:color="#color/rate_app_dialog_positive_button_pressed_background_color_material_light" />
<padding android:left="#dimen/button_padding_horizontal_material"
android:top="#dimen/button_padding_vertical_material"
android:right="#dimen/button_padding_horizontal_material"
android:bottom="#dimen/button_padding_vertical_material" />
</shape>
</inset>
</item>
<!-- normal state -->
<item>
<inset xmlns:android="http://schemas.android.com/apk/res/android"
android:insetLeft="#dimen/button_inset_horizontal_material"
android:insetTop="#dimen/button_inset_vertical_material"
android:insetRight="#dimen/button_inset_horizontal_material"
android:insetBottom="#dimen/button_inset_vertical_material">
<shape android:shape="rectangle">
<corners android:radius="#dimen/control_corner_material" />
<solid android:color="#color/rate_app_dialog_positive_button_background_color_material_light" />
<padding android:left="#dimen/button_padding_horizontal_material"
android:top="#dimen/button_padding_vertical_material"
android:right="#dimen/button_padding_horizontal_material"
android:bottom="#dimen/button_padding_vertical_material" />
</shape>
</inset>
</item>
</selector>
themes.xml
<item name="rateAppDialogPositiveButtonTextColor">#color/rate_app_dialog_positive_button_text_color_material_light</item>
<item name="rateAppDialogPositiveButtonSelector">#drawable/rate_app_dialog_positive_button_selector_material_light</item>
RateAppDialogFragment.java
TypedValue typedValue = new TypedValue();
Resources.Theme theme = this.getContext().getTheme();
theme.resolveAttribute(R.attr.rateAppDialogPositiveButtonTextColor, typedValue, true);
final int rateAppDialogPositiveButtonTextColor = typedValue.data;
theme.resolveAttribute(R.attr.rateAppDialogPositiveButtonSelector, typedValue, true);
final int rateAppDialogPositiveButtonSelectorResourceId = typedValue.resourceId;
dialog.setOnShowListener(new DialogInterface.OnShowListener() {
#Override
public void onShow(DialogInterface d) {
Button positiveButton = dialog.getButton(AlertDialog.BUTTON_POSITIVE);
positiveButton.setTextColor(rateAppDialogPositiveButtonTextColor);
positiveButton.setBackgroundResource(rateAppDialogPositiveButtonSelectorResourceId);
}
});
This works pretty nice for Android 4 and above.
MaterialAlertDialogBuilder(it, R.style.MaterialDialog)
.setTitle(R.string.title_logout)
.setMessage(R.string.msg_logout)
.setNegativeButton("Cancel", null)
.setPositiveButton("Ok") { _, _ ->
vm.logout()
val intent = Intent(context, AuthActivity::class.java)
startActivity(intent)
activity?.finish()
}
.create()
.show()
Create the dialog using the above code.
<style name="MaterialDialog" parent="Theme.MaterialComponents.Light.Dialog">
<item name="android:windowNoTitle">true</item>
<item name="android:buttonBarPositiveButtonStyle">#style/MaterialDialog.ButtonStyle</item>
<item name="android:buttonBarNegativeButtonStyle">#style/MaterialDialog.ButtonStyle</item>
<item name="android:textColorPrimary">#color/black</item>
<item name="colorPrimary">#color/colorAccent</item>
<item name="android:background">#color/white</item>
</style>
<style name="MaterialDialog.ButtonStyle">
<item name="android:background">#color/white</item>
</style>
and add the above styles in your styles

How to set Material design style to disabled EditText (android)?

I'm trying to make my disabled EditText's style like in guidelines:
https://www.google.com/design/spec/components/text-fields.html#text-fields-labels
<EditText
android:id="#+id/account_number"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="#string/test_account"
android:enabled="false" />
I've already implemented material design styles, so all my widgets look material.
The question is: Is there any way to get this dotted underline using styles, without putting additional views?
My styles.xml:
<style name="Theme.Main" parent="#style/Theme.AppCompat.Light.NoActionBar">
<item name="android:editTextStyle">#style/android:Widget.Material.EditText</item>
</style>
Finally I managed to do as you've shown, It looks like
Create dotted.xml inside drawable folder and paste these
<layer-list xmlns:android="http://schemas.android.com/apk/res/android">
<item
android:bottom="1dp"
android:left="-2dp"
android:right="-2dp"
android:top="-2dp">
<shape android:shape="rectangle">
<stroke
android:width="0.5dp"
android:color="#android:color/black" />
<solid android:color="#ffffff" />
<stroke
android:width="1dp"
android:color="#030310"
android:dashGap="5dp"
android:dashWidth="5dp" />
<padding
android:bottom="5dp"
android:left="5dp"
android:right="5dp"
android:top="5dp" />
</shape>
</item>
</layer-list>
Then simply set the android:background attribute to dotted.xml we just created. Your EditText looks like this.
<EditText
android:id="#+id/account_number"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="test account"
android:background="#drawable/dotted"
style="#style/Theme.Main" <!--Its your custom style-->
android:enabled="false" />
AFAIK, there is no "stock" way. Take the material design guidelines as it is, a guideline ;)
Finally I ended up with a custom view. It might be not the most elegant solution but it solves my task.
Hope it will be helpful for someone.
DisabledTextField.java:
package com.kabunov.example.ui.common;
import android.content.Context;
import android.content.res.TypedArray;
import android.text.TextUtils;
import android.util.AttributeSet;
import android.view.View;
import android.widget.FrameLayout;
import android.widget.TextView;
import com.kabunov.example.R;
public final class DisabledTextField extends FrameLayout {
private TextView tvCaption;
private TextView tvText;
private View divider;
public DisabledTextField(final Context context) {
this(context, null);
}
public DisabledTextField(final Context context, final AttributeSet attrs) {
this(context, attrs, 0);
}
public DisabledTextField(final Context context, final AttributeSet attrs, final int defStyleAttr) {
super(context, attrs, defStyleAttr);
View.inflate(getContext(), R.layout.component_disabled_text_field, this);
tvCaption = (TextView) findViewById(R.id.caption);
tvText = (TextView) findViewById(R.id.value);
final TypedArray typedArray = context.obtainStyledAttributes(attrs, R.styleable.DisabledTextField);
if (null != typedArray) {
final String captionText = typedArray.getString(R.styleable.DisabledTextField_caption);
if (TextUtils.isEmpty(captionText)) {
tvCaption.setVisibility(GONE);
} else {
tvCaption.setText(captionText);
tvCaption.setVisibility(VISIBLE);
}
final String text = typedArray.getString(R.styleable.DisabledTextField_disabledText);
tvText.setText(text);
typedArray.recycle();
}
}
public final void setCaption(final CharSequence caption) {
this.tvCaption.setText(caption);
this.tvCaption.setVisibility(VISIBLE);
}
public final void setDisabledText(final CharSequence value) {
this.tvText.setText(value);
}
}
/layout/component_disabled_text.xml:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<TextView
android:id="#+id/caption"
android:layout_width="match_parent"
android:layout_height="wrap_content"
style="#style/DisabledTextFieldCaption"/>
<TextView
android:id="#+id/value"
android:layout_width="match_parent"
android:layout_height="wrap_content"
style="#style/DisabledTextFieldValue"/>
<View
android:id="#+id/divider"
android:layout_width="match_parent"
android:layout_height="1dp"
android:background="#drawable/disabled_text_field_background"
android:layerType="software"/>
</LinearLayout>
/values/attributes_disabled_text_field.xml:
<?xml version="1.0" encoding="utf-8"?>
<resources>
<declare-styleable name="DisabledTextField">
<attr name="caption" format="string"/>
<attr name="disabledText" format="string"/>
</declare-styleable>
</resources>
/drawable/disabled_text_field_background.xml:
<?xml version="1.0" encoding="utf-8"?>
<layer-list xmlns:android="http://schemas.android.com/apk/res/android">
<item
android:bottom="-1dp"
android:left="-1dp"
android:right="-1dp"
android:top="0dp">
<shape android:shape="rectangle">
<stroke
android:width="1dp"
android:color="#color/text_color_disabled_text_view"
android:dashGap="2dp"
android:dashWidth="1dp" />
<solid android:color="#android:color/transparent" />
</shape>
</item>
</layer-list>
/values/styles.xml:
<?xml version="1.0" encoding="utf-8"?>
<resources>
<color name="text_color_disabled_text_view">#61000000</color>
<style name="DisabledTextFieldCaption">
<item name="android:textSize">12sp</item>
<item name="android:textColor">#color/text_color_disabled_text_view</item>
</style>
<style name="DisabledTextFieldValue">
<item name="android:layout_marginTop">3dp</item>
<item name="android:layout_marginBottom">8dp</item>
<item name="android:textSize">16sp</item>
<item name="android:textColor">#color/text_color_disabled_text_view</item>
</style>
</resources>
Example of usage:
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:custom="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="match_parent">
<com.kabunov.example.ui.common.DisabledTextField
android:id="#+id/example"
android:layout_width="match_parent"
android:layout_height="wrap_content"
custom:caption="Some caption"
custom:disabledText="Disabled text"/>
</LinearLayout>
And the result:

How to make custom dialog with rounded corners in android

What I am trying to do: I am trying to make a custom dialog in android With rounded corners.
What is happening: I am able to make custom dialog but it doesn't have rounded corners. I tried adding a selector but still I couldn't achieve rounded corners.
Below is my code for the same:
Java code:
private void launchDismissDlg() {
dialog = new Dialog(getActivity(), android.R.style.Theme_Dialog);
dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
dialog.setContentView(R.layout.dlg_dismiss);
dialog.setCanceledOnTouchOutside(true);
Button btnReopenId = (Button) dialog.findViewById(R.id.btnReopenId);
Button btnCancelId = (Button) dialog.findViewById(R.id.btnCancelId);
btnReopenId.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
}
});
btnCancelId.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
}
});
dialog.setCanceledOnTouchOutside(false);
dialog.getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN);
dialog.getWindow().setLayout(LayoutParams.MATCH_PARENT,LayoutParams.WRAP_CONTENT);
dialog.show();
}
xml code:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#android:color/white"
android:orientation="vertical" >
<TableLayout
android:layout_width="match_parent"
android:layout_height="wrap_content" >
<TableRow
android:id="#+id/tableRow1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="20dp"
android:gravity="center" >
<TextView
android:id="#+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:gravity="center"
android:text=""I WOULD LIKE TO DISMISS THE VENDOR""
android:textColor="#color/col_dlg_blue_light"
android:textSize="14sp"
android:textStyle="bold" />
</TableRow>
<TableRow
android:id="#+id/tableRow2"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="5dp"
android:gravity="center" >
<TextView
android:id="#+id/textView2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:gravity="center"
android:text="BECAUSE"
android:textColor="#android:color/black"
android:textStyle="bold" />
</TableRow>
<TableRow
android:id="#+id/tableRow4"
android:layout_width="match_parent"
android:layout_height="wrap_content" >
<Button
android:id="#+id/btnReopenId"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1"
android:background="#color/col_dlg_green_light"
android:text="REOPEN"
android:padding="5dp"
android:textSize="14sp"
android:textColor="#android:color/white"
android:textStyle="bold" />
<Button
android:id="#+id/btnCancelId"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1"
android:background="#color/col_dlg_pink_light"
android:text="CANCEL"
android:padding="5dp"
android:textSize="14sp"
android:textColor="#android:color/white"
android:textStyle="bold" />
</TableRow>
</TableLayout>
</LinearLayout>
Create an XML file in drawable, say dialog_bg.xml:
<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android">
<solid
android:color="#color/white"/>
<corners
android:radius="30dp" />
<padding
android:left="10dp"
android:top="10dp"
android:right="10dp"
android:bottom="10dp" />
</shape>
set it as the background in your layout XML:
android:background="#drawable/dialog_bg"
Set the background of the dialog's root view to transparent, because Android puts your dialog layout within a root view that hides the corners in your custom layout.
Java:
dialog.getWindow().setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));
Kotlin:
dialog.window?.setBackgroundDrawable(ColorDrawable(Color.TRANSPARENT))
With the Androidx library and Material Components Theme you can override the getTheme() method:
import androidx.fragment.app.DialogFragment
class RoundedDialog: DialogFragment() {
override fun getTheme() = R.style.RoundedCornersDialog
//....
}
with:
<style name="RoundedCornersDialog" parent="#style/Theme.MaterialComponents.Dialog">
<item name="dialogCornerRadius">16dp</item>
</style>
Or you can use the MaterialAlertDialogBuilder included in the Material Components Library:
import androidx.fragment.app.DialogFragment
import com.google.android.material.dialog.MaterialAlertDialogBuilder
class RoundedAlertDialog : DialogFragment() {
//...
override fun onCreateDialog(savedInstanceState: Bundle?): Dialog {
return MaterialAlertDialogBuilder(requireActivity(), R.style.MaterialAlertDialog_rounded)
.setTitle("Test")
.setMessage("Message")
.setPositiveButton("OK", null)
.create()
}
}
with:
<style name="MaterialAlertDialog_rounded" parent="#style/ThemeOverlay.MaterialComponents.MaterialAlertDialog">
<item name="shapeAppearanceOverlay">#style/DialogCorners</item>
</style>
<style name="DialogCorners">
<item name="cornerFamily">rounded</item>
<item name="cornerSize">16dp</item>
</style>
If you don't need a DialogFragment just use the MaterialAlertDialogBuilder.
You need to do the following:
Create a background with rounded corners for the Dialog's background:
<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
android:shape="rectangle" >
<solid android:color="#fff" />
<corners
android:bottomLeftRadius="8dp"
android:bottomRightRadius="8dp"
android:topLeftRadius="8dp"
android:topRightRadius="8dp" />
</shape>
Now in your Dialog's XML file in the root layout use that background with required margin:
android:layout_marginLeft="20dip"
android:layout_marginRight="20dip"
android:background="#drawable/dialog_background"
finally in the java part you need to do this:
dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
dialog.setContentView(layoutResId);
View v = getWindow().getDecorView();
v.setBackgroundResource(android.R.color.transparent);
This works perfectly for me.
dialog.getWindow().setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));
this works for me
Setting
dialog.getWindow().setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));
will prevent dialog to cast a shadow.
Solution is to use
dialog.getWindow().setBackgroundDrawableResource(R.drawable.dialog_rounded_background);
where is R.drawable.dialog_rounded_background
<?xml version="1.0" encoding="utf-8"?>
<layer-list xmlns:android="http://schemas.android.com/apk/res/android" >
<item>
<shape android:shape="rectangle" android:padding="10dp">
<solid
android:color="#color/dialog_bg_color"/>
<corners
android:radius="30dp" />
</shape>
</item>
</layer-list>
If you use Material Components:
CustomDialog.kt
class CustomDialog: DialogFragment() {
override fun getTheme() = R.style.RoundedCornersDialog
}
styles.xml
<style name="RoundedCornersDialog" parent="Theme.MaterialComponents.Dialog">
<item name="dialogCornerRadius">dimen</item>
</style>
dimen.xml
<?xml version="1.0" encoding="utf-8"?>
<resources>
<integer name="weight">1</integer>
<dimen name="dialog_top_radius">21dp</dimen>
<dimen name="textview_dialog_head_min_height">50dp</dimen>
<dimen name="textview_dialog_drawable_padding">5dp</dimen>
<dimen name="button_dialog_layout_margin">3dp</dimen>
</resources>
styles.xml
<style name="TextView.Dialog">
<item name="android:paddingLeft">#dimen/dimen_size</item>
<item name="android:paddingRight">#dimen/dimen_size</item>
<item name="android:gravity">center_vertical</item>
<item name="android:textColor">#color/black</item>
</style>
<style name="TextView.Dialog.Head">
<item name="android:minHeight">#dimen/textview_dialog_head_min_height</item>
<item name="android:textColor">#color/white</item>
<item name="android:background">#drawable/dialog_title_style</item>
<item name="android:drawablePadding">#dimen/textview_dialog_drawable_padding</item>
</style>
<style name="TextView.Dialog.Text">
<item name="android:textAppearance">#style/Font.Medium.16</item>
</style>
<style name="Button" parent="Base.Widget.AppCompat.Button">
<item name="android:layout_height">#dimen/button_min_height</item>
<item name="android:layout_width">match_parent</item>
<item name="android:textColor">#color/white</item>
<item name="android:gravity">center</item>
<item name="android:textAppearance">#style/Font.Medium.20</item>
</style>
<style name="Button.Dialog">
<item name="android:layout_weight">#integer/weight</item>
<item name="android:layout_margin">#dimen/button_dialog_layout_margin</item>
</style>
<style name="Button.Dialog.Middle">
<item name="android:background">#drawable/button_primary_selector</item>
</style>
dialog_title_style.xml
<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
android:shape="rectangle">
<gradient
android:angle="270"
android:endColor="#color/primaryDark"
android:startColor="#color/primaryDark" />
<corners
android:topLeftRadius="#dimen/dialog_top_radius"
android:topRightRadius="#dimen/dialog_top_radius" />
</shape>
dialog_background.xml
<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android">
<solid android:color="#color/backgroundDialog" />
<corners
android:topLeftRadius="#dimen/dialog_top_radius"
android:topRightRadius="#dimen/dialog_top_radius" />
<padding />
</shape>
dialog_one_button.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#drawable/dailog_background"
android:orientation="vertical">
<TextView
android:id="#+id/dialogOneButtonTitle"
style="#style/TextView.Dialog.Head"
android:text="Process Completed" />
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginBottom="16dp"
android:layout_marginLeft="16dp"
android:layout_marginRight="16dp"
android:orientation="vertical">
<TextView
android:id="#+id/dialogOneButtonText"
style="#style/TextView.Dialog.Text"
android:text="Return the main menu" />
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">
<Button
android:id="#+id/dialogOneButtonOkButton"
style="#style/Button.Dialog.Middle"
android:text="Ok" />
</LinearLayout>
</LinearLayout>
</LinearLayout>
OneButtonDialog.java
package com.example.sametoztoprak.concept.dialogs;
import android.app.Dialog;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.view.Window;
import android.widget.Button;
import android.widget.TextView;
import com.example.sametoztoprak.concept.R;
import com.example.sametoztoprak.concept.models.DialogFields;
/**
* Created by sametoztoprak on 26/09/2017.
*/
public class OneButtonDialog extends Dialog implements View.OnClickListener {
private static OneButtonDialog oneButtonDialog;
private static DialogFields dialogFields;
private Button dialogOneButtonOkButton;
private TextView dialogOneButtonText;
private TextView dialogOneButtonTitle;
public OneButtonDialog(AppCompatActivity activity) {
super(activity);
}
public static OneButtonDialog getInstance(AppCompatActivity activity, DialogFields dialogFields) {
OneButtonDialog.dialogFields = dialogFields;
return oneButtonDialog = (oneButtonDialog == null) ? new OneButtonDialog(activity) : oneButtonDialog;
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.dialog_one_button);
getWindow().setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));
dialogOneButtonTitle = (TextView) findViewById(R.id.dialogOneButtonTitle);
dialogOneButtonText = (TextView) findViewById(R.id.dialogOneButtonText);
dialogOneButtonOkButton = (Button) findViewById(R.id.dialogOneButtonOkButton);
dialogOneButtonOkButton.setOnClickListener(this);
}
#Override
protected void onStart() {
super.onStart();
dialogOneButtonTitle.setText(dialogFields.getTitle());
dialogOneButtonText.setText(dialogFields.getText());
dialogOneButtonOkButton.setText(dialogFields.getOneButton());
}
#Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.dialogOneButtonOkButton:
break;
default:
break;
}
dismiss();
}
}
I made a new way without having a background drawable is that make it have CardView as parent and give it a app:cardCornerRadius="20dp" and then add this in the java class dialog.getWindow().setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));
It's another way to make it .
You can simply use MaterialAlertDialogBuilder to create custom dialog with rounded corners.
First create a style for the material dialog like this :
<style name="MyRounded.MaterialComponents.MaterialAlertDialog" parent="#style/ThemeOverlay.MaterialComponents.MaterialAlertDialog">
<item name="shapeAppearanceOverlay">#style/ShapeAppearanceOverlay.App.CustomDialog.Rounded
</item>
<item name="colorSurface">#color/YOUR_COLOR</item>
</style>
<style name="ShapeAppearanceOverlay.App.CustomDialog.Rounded" parent="">
<item name="cornerFamily">rounded</item>
<item name="cornerSize">10dp</item>
</style>
then create a Alert Dialog object in Java class like this :
AlertDialog alertDialog = new MaterialAlertDialogBuilder(this,R.style.MyRounded_MaterialComponents_MaterialAlertDialog) // for fragment you can use getActivity() instead of this
.setView(R.layout.custom_layout) // custom layout is here
.show();
final EditText editText = alertDialog.findViewById(R.id.custom_layout_text); // access to text view of custom layout
Button btn = alertDialog.findViewById(R.id.custom_layout_btn);
btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Log.d(TAG, "onClick: " + editText.getText().toString());
}
});
That's all you need to do.
For anyone who like do things in XML, specially in case where you are using Navigation architecture component actions in order to navigate to dialogs
You can use:
<style name="DialogStyle" parent="ThemeOverlay.MaterialComponents.Dialog.Alert">
<!-- dialog_background is drawable shape with corner radius -->
<item name="android:background">#drawable/dialog_background</item>
<item name="android:windowBackground">#android:color/transparent</item>
</style>
simplest way is to use from
CardView and its card:cardCornerRadius
<?xml version="1.0" encoding="utf-8"?>
<android.support.v7.widget.CardView
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:card="http://schemas.android.com/apk/res-auto"
android:orientation="vertical"
android:id="#+id/cardlist_item"
android:layout_width="match_parent"
android:layout_height="130dp"
card:cardCornerRadius="40dp"
android:layout_marginLeft="8dp"
android:layout_marginRight="8dp"
android:layout_marginTop="5dp"
android:layout_marginBottom="5dp"
android:background="#color/white">
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_margin="12sp"
android:orientation="vertical"
android:weightSum="1">
</RelativeLayout>
</android.support.v7.widget.CardView>
And when you are creating your Dialog
dialog.getWindow().setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));
You can use the shape for the background as-
<shape xmlns:android="http://schemas.android.com/apk/res/android"
android:shape="rectangle">
<solid android:color="#android:color/transparent"/>
<corners android:radius="10dp" />
<padding android:left="10dp" android:right="10dp"/>
</shape>
Have a look on this for the details.
Here is a Basic Solution:
<style name="Style_Dialog_Rounded_Corner" parent="Theme.AppCompat.Light.Dialog.Alert">
<item name="android:windowBackground">#drawable/dialog_rounded_corner</item>
<item name="android:windowMinWidthMinor">85%</item>
</style>
in Drawable create shape:
<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android">
<solid android:color="#FFFFFF" />
<corners android:radius="12dp" />
</shape>
Pass style in Builder Constructor
AlertDialog alert = new AlertDialog.Builder(MainActivity.this,R.style.Style_Dialog_Rounded_Corner).create();
Here is the complete solution if you want to control the corner radius of the dialog and preserve elevation shadow
Dialog:
class OptionsDialog: DialogFragment() {
override fun onCreateView(inflater: LayoutInflater, container: ViewGroup, savedInstanceState: Bundle?): View {
dialog?.window?.setBackgroundDrawable(ColorDrawable(Color.TRANSPARENT))
return inflater.inflate(R.layout.dialog_options, container)
}
}
dialog_options.xml layout:
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="wrap_content"
android:layout_height="wrap_content">
<androidx.cardview.widget.CardView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_margin="40dp"
app:cardElevation="20dp"
app:cardCornerRadius="12dp">
<androidx.constraintlayout.widget.ConstraintLayout
id="#+id/actual_content_goes_here"
android:layout_width="wrap_content"
android:layout_height="wrap_content">
</androidx.constraintlayout.widget.ConstraintLayout>
</androidx.cardview.widget.CardView>
</FrameLayout>
The key is to wrap the CardView with another ViewGroup (here FrameLayout) and set margins to create space for the elevation shadow.
For API level >= 28 available attribute android:dialogCornerRadius . To support previous API versions need use
<style name="RoundedDialog" parent="Theme.AppCompat.Light.Dialog.Alert">
<item name="android:windowBackground">#drawable/dialog_bg</item>
</style>
where dialog_bg.xml
<?xml version="1.0" encoding="utf-8"?>
<layer-list xmlns:android="http://schemas.android.com/apk/res/android">
<item >
<shape >
<solid android:color="#android:color/transparent" />
</shape>
</item>
<item
android:left="16dp"
android:right="16dp">
<shape>
<solid
android:color="#color/white"/>
<corners
android:radius="8dp" />
<padding
android:left="16dp"
android:right="16dp" />
</shape>
</item>
</layer-list>
In Kotlin, I am using a class DoubleButtonDialog.Java with line window?.setBackgroundDrawable(ColorDrawable(Color.TRANSPARENT)) as important one
class DoubleButtonDialog(context: Context) : Dialog(context, R.style.DialogTheme) {
private var cancelableDialog: Boolean = true
private var titleDialog: String? = null
private var messageDialog: String? = null
private var leftButtonDialog: String = "Yes"
// private var rightButtonDialog: String? = null
private var onClickListenerDialog: OnClickListener? = null
override fun onCreate(savedInstanceState: Bundle?) {
window?.setBackgroundDrawable(ColorDrawable(Color.TRANSPARENT))
//requestWindowFeature(android.view.Window.FEATURE_NO_TITLE)
setCancelable(cancelableDialog)
setContentView(R.layout.dialog_double_button)
// val btnNegative = findViewById<Button>(R.id.btnNegative)
// btnNegative.visibility = View.GONE
// if (rightButtonDialog != null) {
// btnNegative.visibility = View.VISIBLE
// btnNegative.text = rightButtonDialog
// btnNegative.setOnClickListener {
// dismiss()
// onClickListenerDialog?.onClickCancel()
// }
// }
val btnPositive = findViewById<Button>(R.id.btnPositive)
btnPositive.text = leftButtonDialog
btnPositive.setOnClickListener {
onClickListenerDialog?.onClick()
dismiss()
}
(findViewById<TextView>(R.id.title)).text = titleDialog
(findViewById<TextView>(R.id.message)).text = messageDialog
super.onCreate(savedInstanceState)
}
constructor(
context: Context, cancelableDialog: Boolean, titleDialog: String?,
messageDialog: String, leftButtonDialog: String, /*rightButtonDialog: String?,*/
onClickListenerDialog: OnClickListener
) : this(context) {
this.cancelableDialog = cancelableDialog
this.titleDialog = titleDialog
this.messageDialog = messageDialog
this.leftButtonDialog = leftButtonDialog
// this.rightButtonDialog = rightButtonDialog
this.onClickListenerDialog = onClickListenerDialog
}
}
interface OnClickListener {
// fun onClickCancel()
fun onClick()
}
In layout, we can create a dialog_double_button.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"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:layout_margin="#dimen/dimen_10"
android:background="#drawable/bg_double_button"
android:orientation="vertical"
android:padding="#dimen/dimen_5">
<TextView
android:id="#+id/title"
style="#style/TextViewStyle"
android:layout_gravity="center_horizontal"
android:layout_margin="#dimen/dimen_10"
android:fontFamily="#font/campton_semi_bold"
android:textColor="#color/red_dark4"
android:textSize="#dimen/text_size_24"
tools:text="#string/dial" />
<TextView
android:id="#+id/message"
style="#style/TextViewStyle"
android:layout_gravity="center_horizontal"
android:layout_margin="#dimen/dimen_10"
android:gravity="center"
android:textColor="#color/semi_gray_2"
tools:text="#string/diling_police_number" />
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="#dimen/dimen_10"
android:gravity="center"
android:orientation="horizontal"
android:padding="#dimen/dimen_5">
<!--<Button
android:id="#+id/btnNegative"
style="#style/ButtonStyle"
android:layout_width="0dp"
android:layout_height="#dimen/dimen_40"
android:layout_marginEnd="#dimen/dimen_10"
android:layout_weight=".4"
android:text="#string/cancel" />-->
<Button
android:id="#+id/btnPositive"
style="#style/ButtonStyle"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:backgroundTint="#color/red_dark4"
android:fontFamily="#font/campton_semi_bold"
android:padding="#dimen/dimen_10"
android:text="#string/proceed"
android:textAllCaps="false"
android:textColor="#color/white"
android:textSize="#dimen/text_size_20" />
</LinearLayout>
</LinearLayout>
then use drawable.xml as
<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android">
<solid
android:color="#color/white"/>
<corners
android:radius="#dimen/dimen_10" />
<padding
android:left="#dimen/dimen_10"
android:top="#dimen/dimen_10"
android:right="#dimen/dimen_10"
android:bottom="#dimen/dimen_10" />
</shape>
Create a xml in drawable ,say customd.xml.
then set it at background in your custom Dialog layout xml:
android:background="#drawable/customd"
finally in the java part for custom Dialog class you need to do this:
public class Customdialoque extends DialogFragment {
public View onCreateView(#NonNull LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
getDialog().getWindow().setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));
View view = inflater.inflate(R.layout.activity_customdialoque, container, false);
return view;
}
I implemented rounded dialog using CardView in the custom layout and setting its corner radius.
Here's my xml code.
<?xml version="1.0" encoding="utf-8"?>
<androidx.cardview.widget.CardView
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:id="#+id/bottomSheet"
android:layout_width="match_parent"
android:layout_margin="#dimen/padding_5dp"
app:cardCornerRadius="#dimen/dimen_20dp"
android:layout_height="wrap_content">
<androidx.constraintlayout.widget.ConstraintLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#drawable/main_gradient_bg"
android:paddingBottom="32dp">
<TextView
android:id="#+id/subdomain_label"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginStart="#dimen/margin_32dp"
android:layout_marginLeft="#dimen/margin_32dp"
android:layout_marginTop="#dimen/margin_50dp"
android:fontFamily="#font/nunito_sans"
android:text="#string/enter_subdomain"
android:textColor="#color/white"
android:textSize="#dimen/size_18sp"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintTop_toTopOf="parent" />
<ImageView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="#dimen/dimen_45dp"
app:layout_constraintLeft_toRightOf="#id/subdomain_label"
app:layout_constraintTop_toTopOf="parent"
app:srcCompat="#drawable/ic_baseline_info_24" />
<EditText
android:id="#+id/subdomain_edit_text_bottom_sheet"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginStart="#dimen/dimen_20dp"
android:layout_marginLeft="#dimen/dimen_20dp"
android:layout_marginEnd="#dimen/dimen_20dp"
android:layout_marginRight="#dimen/dimen_20dp"
android:textColor="#color/white"
android:theme="#style/EditTextTheme"
app:layout_constraintTop_toBottomOf="#id/subdomain_label" />
<Button
android:id="#+id/proceed_btn"
android:layout_width="#dimen/dimen_150dp"
android:layout_height="#dimen/margin_50dp"
android:layout_marginTop="#dimen/margin_30dp"
android:background="#drawable/primary_btn_bg"
android:text="#string/proceed"
android:textAllCaps="false"
android:textColor="#color/white"
android:textSize="#dimen/size_18sp"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintTop_toBottomOf="#id/subdomain_edit_text_bottom_sheet" />
</androidx.constraintlayout.widget.ConstraintLayout>
</androidx.cardview.widget.CardView>
After that, i called it in Kotlin as follows :-
val builder = AlertDialog.Builder(mContext)
val viewGroup: ViewGroup = findViewById(android.R.id.content)
val dialogView: View =
LayoutInflater.from(mContext).inflate(R.layout.subdomain_bottom_sheet,
viewGroup, false)
val alertDialog: AlertDialog = builder.create()
alertDialog.setView(dialogView,0,0,0,0)
alertDialog.show()
val windowParam = WindowManager.LayoutParams()
windowParam.copyFrom(alertDialog.window!!.attributes)
windowParam.width = AppConstant.getDisplayMetricsWidth(mContext) - 100
windowParam.height = WindowManager.LayoutParams.WRAP_CONTENT
windowParam.gravity = Gravity.CENTER
alertDialog.window!!.attributes = windowParam
alertDialog.window!!.setBackgroundDrawable
(ColorDrawable(Color.TRANSPARENT))
Where last line is very important. Missing that would cause a color(mostly white) to show behind the corners.
The accepted answer did round the corners for me, but unless I switched to a Material design theme, making the window background transparent had no effect and I still saw a square, shadowed background of the dialog inside my rounded background. And I don't want to switch to a Material theme because that changes the functionality of date and time pickers.
Instead, I had to hide the backgrounds of several subviews of the dialog in order to see the rounded background. And after doing all that, it was easier just to add the rounded background in code, too. So here's a fully programmatic (no XML) solution. This is in the onStart method of my DialogFragment subclass:
// add rounded corners
val backgroundShape = GradientDrawable()
backgroundShape.cornerRadius = 10.0f
backgroundShape.setColor(Color.BLUE)
this.dialog.window?.decorView?.background = backgroundShape
// make the backgrounds of the dialog elements transparent so we can see the rounded corner background
val topPanelId = this.context.resources.getIdentifier("topPanel", "id", "android")
val topPanel = this.dialog.findViewById<View>(topPanelId)
topPanel?.setBackgroundColor(Color.TRANSPARENT)
val contentPanelId = this.context.resources.getIdentifier("contentPanel", "id", "android")
val contentPanel = this.dialog.findViewById<View>(contentPanelId)
contentPanel?.setBackgroundColor(Color.TRANSPARENT)
val customPanelId = this.context.resources.getIdentifier("customPanel", "id", "android")
val customPanel = this.dialog.findViewById<View>(customPanelId)
customPanel?.setBackgroundColor(Color.TRANSPARENT)
val buttonPanelId = this.context.resources.getIdentifier("buttonPanel", "id", "android")
val buttonPanel = this.dialog.findViewById<View>(buttonPanelId)
buttonPanel?.setBackgroundColor(Color.TRANSPARENT)
Here is another way in kotlin:
val model = ShapeAppearanceModel()
.toBuilder()
.setAllCorners(CornerFamily.ROUNDED, 32.0f)
.build()
val shape = MaterialShapeDrawable(model)
shape.fillColor = ContextCompat.getColorStateList(context, R.color.white)
ViewCompat.setBackground(dialogContentView, shape)
And then change the dialog window
dialog?.window?.setBackgroundDrawableResource(android.R.color.transparent)

Android: change background color View onClick Button

How I can change the background color to a View this under a button when I click the button? I've tried a selector does not work because the View not change the color. What is the problem?
This is my code:
XML
...
<View
android:id="#+id/viewPlanos2"
android:layout_width="match_parent"
android:layout_height="3dp"
android:layout_gravity="center" />
<Button
android:id="#+id/button"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_gravity="center"
android:layout_weight="1"
android:background="#color/transparente"
android:drawableTop="#drawable/buttonimage"
android:gravity="center"
android:paddingTop="50dp" />
<View
android:id="#+id/viewPlanos1"
android:layout_width="match_parent"
android:layout_height="3dp"
android:layout_gravity="center" />
...
JAVA
View linea2 = (View)findViewById(R.id.viewPlanos2);
linea2.setBackgroundColor(getResources().getColor(R.drawable.linea_verde));
linea_verde
<item android:state_pressed="true"><shape>
<gradient android:angle="90" android:endColor="#color/azul" android:startColor="#color/azulOscuro" />
</shape></item>
<item android:state_focused="true"><shape>
<gradient android:angle="90" android:endColor="#color/azul" android:startColor="#color/azulOscuro" />
</shape></item>
<item><shape>
<solid android:color="#color/rojo" />
</shape></item>
EDIT:
I have tried:
public void onClick(View v) {
if(v == botonMetro) {
linea2.setBackgroundResource(R.drawable.linea_verde);
and
linea2.setBackgroundColor(getResources().getColor(R.drawable.linea_verde));
}
}
But the code not work
You are wrongly using drawable use this one one
view.setBackgroundResource(R.drawable.linea_verde)
as you say change the background color to a View this under a button when I click the button
do like this
button.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// change color of your view here
linea2.setBackgroundColor(getResources().getColor(R.drawable.linea_verde));
}
});
setBackgroundColor() is for colors only, but it seems your using a state list drawable. If you are sure you want to use a different color depending on the Button's state, set the state list drawable using this code:
view.setBackgroundDrawable(R.drawable.linea_verde);
Otherwise, just set the background color using
view.setBackgroundColor(getResources().getColor(R.drawable.yourcolor);
But in this case, use a click listener, and also make sure to actually use a color resource, e.g.:
<?xml version="1.0" encoding="utf-8"?>
<resources>
<color name="opaque_red">#f00</color>
<color name="translucent_red">#80ff0000</color>
</resources>
You can also do like this.
android:background="#drawable/linea_verde"
If you would like to apply default background of selected item you could use background attribute with android ?attr.
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="?attr/selectableItemBackground" />
selectableItemBackground attribute will use proper drawable according to Android version. On pre-lollipop it will use solid background, but on lollipop devices the ripple effect will be used.
Code from: com.android.support/appcompat-v7/23.0.0/res/values/values.xml
<item name="selectableItemBackground">#drawable/abc_item_background_holo_dark</item>
public void onClick(View v) {
int id = v.getId();
if(id == R.id.button) {
linea2.setBackgroundResource(R.drawable.linea_verde);
}
}
I think you were comparing the view the wrong way. I just happened to stumble to this question and since it is not marked as answered, this might help others.
Create two separate files for your shapes and change the background of your view after button click:
private boolean isPressed = false;
public void onClick(View v) {
if(v == botonMetro) {
if(isPressed){
linea2.setBackgroundResource(R.drawable.pressed_shape);
} else{
linea2.setBackgroundResource(R.drawable.un_pressed_shape);
}
isPressed = !isPressed;
}
}

Custom checkbox image android

Is there an easy way to use a custom image for a checkbox? I'm looking to duplicate the "starred" behavior of gmail. So I want to have a checkbox that, when checked, is a filled in star. And when unchecked is an empty star. Do I have to use an imageview and do my own logic myself?
Create a drawable checkbox selector:
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android" >
<item android:drawable="#drawable/checkbox"
android:state_checked="false"/>
<item android:drawable="#drawable/checkboxselected"
android:state_checked="true"/>
<item android:drawable="#drawable/checkbox"/>
</selector>
Make sure your checkbox is like this android:button="#drawable/checkbox_selector"
<CheckBox
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:button="#drawable/checkbox_selector"
android:text="CheckBox"
android:textAppearance="?android:attr/textAppearanceLarge"
android:textColor="#color/Black" />
Checkboxes being children of Button you can just give your checkbox a background image with several states as described here, under "Button style":
...and exemplified here:
Copy the btn_check.xml from android-sdk/platforms/android-#/data/res/drawable to your project's drawable folder and change the 'on' and 'off' image states to your custom images.
Then your xml will just need android:button="#drawable/btn_check"
<CheckBox
android:button="#drawable/btn_check"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:checked="true" />
If you want to use different default android icons, you can use android:button="#android:drawable/..."
res/drawable/day_selector.xml
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android" >
<item android:drawable="#drawable/dayselectionunselected"
android:state_checked="false"/>
<item android:drawable="#drawable/daysselectionselected"
android:state_checked="true"/>
<item android:drawable="#drawable/dayselectionunselected"/>
</selector>
res/layout/my_layout.xml
<CheckBox
android:id="#+id/check"
android:layout_width="39dp"
android:layout_height="39dp"
android:background="#drawable/day_selector"
android:button="#null"
android:gravity="center"
android:text="S"
android:textColor="#color/black"
android:textSize="12sp" />
If you have Android open source code, you can find the styles definition under:
src/frameworks/base/core/res/res/values
<style name="Widget.CompoundButton.CheckBox">
<item name="android:background">
#android:drawable/btn_check_label_background
</item>
<item name="android:button">
?android:attr/listChoiceIndicatorMultiple
</item>
</style>
Based on the Enselic and Rahul answers.
It works for me (before and after API 21):
<CheckBox
android:id="#+id/checkbox"
android:layout_width="40dp"
android:layout_height="40dp"
android:text=""
android:gravity="center"
android:background="#drawable/checkbox_selector"
android:button="#null"
app:buttonCompat="#null" />
Try it -
package com;
import android.content.Context;
import android.content.res.TypedArray;
import android.util.AttributeSet;
import android.view.View;
import android.widget.ImageView;
public class CheckBoxImageView extends ImageView implements View.OnClickListener {
boolean checked;
int defImageRes;
int checkedImageRes;
OnCheckedChangeListener onCheckedChangeListener;
public CheckBoxImageView(Context context, AttributeSet attr, int defStyle) {
super(context, attr, defStyle);
init(attr, defStyle);
}
public CheckBoxImageView(Context context, AttributeSet attr) {
super(context, attr);
init(attr, -1);
}
public CheckBoxImageView(Context context) {
super(context);
}
public boolean isChecked() {
return checked;
}
public void setChecked(boolean checked) {
this.checked = checked;
setImageResource(checked ? checkedImageRes : defImageRes);
}
private void init(AttributeSet attributeSet, int defStyle) {
TypedArray a = null;
if (defStyle != -1)
a = getContext().obtainStyledAttributes(attributeSet, R.styleable.CheckBoxImageView, defStyle, 0);
else
a = getContext().obtainStyledAttributes(attributeSet, R.styleable.CheckBoxImageView);
defImageRes = a.getResourceId(0, 0);
checkedImageRes = a.getResourceId(1, 0);
checked = a.getBoolean(2, false);
a.recycle();
setImageResource(checked ? checkedImageRes : defImageRes);
setOnClickListener(this);
}
#Override
public void onClick(View v) {
checked = !checked;
setImageResource(checked ? checkedImageRes : defImageRes);
onCheckedChangeListener.onCheckedChanged(this, checked);
}
public void setOnCheckedChangeListener(OnCheckedChangeListener onCheckedChangeListener) {
this.onCheckedChangeListener = onCheckedChangeListener;
}
public static interface OnCheckedChangeListener {
void onCheckedChanged(View buttonView, boolean isChecked);
}
}
Add this attrib -
<declare-styleable name="CheckBoxImageView">
<attr name="default_img" format="integer"/>
<attr name="checked_img" format="integer"/>
<attr name="checked" format="boolean"/>
</declare-styleable>
Use like -
<com.adonta.ziva.consumer.wrapper.CheckBoxImageView
xmlns:app="http://schemas.android.com/apk/res-auto"
android:id="#+id/checkBox"
android:layout_width="40dp"
android:layout_height="40dp"
android:layout_alignParentRight="true"
android:layout_centerVertical="true"
android:clickable="true"
android:padding="5dp"
app:checked_img="#drawable/check_box_checked"
app:default_img="#drawable/check_box" />
It will fix all your porblems.
Another option is to use a ToggleButton with null background and a custom button.
Bellow an example that includes a selector to the text color as well.
<ToggleButton
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:button="#drawable/toggle_selector"
android:background="#null"
android:paddingLeft="10dp"
android:layout_centerHorizontal="true"
android:gravity="center"
android:textColor="#drawable/toggle_text"
android:textOn="My on state"
android:textOff="My off state" />
toggle_selector.xml
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item
android:state_checked="true"
android:drawable="#drawable/state_on" />
<item
android:drawable="#drawable/state_off" />
</selector>
toggle_text.xml
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item
android:state_checked="true"
android:color="#color/app_color" />
<item
android:color="#android:color/darker_gray" />
</selector>
If you are using custom adapters than android:focusable="false" and android:focusableInTouchMode="false" are nessesury to make list items clickable while using checkbox.
<CheckBox
android:id="#+id/checkbox_fav"
android:focusable="false"
android:focusableInTouchMode="false"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:button="#drawable/checkbox_layout"/>
In drawable>checkbox_layout.xml
<selector xmlns:android="http://schemas.android.com/apk/res/android" >
<item android:drawable="#drawable/uncked_checkbox"
android:state_checked="false"/>
<item android:drawable="#drawable/selected_checkbox"
android:state_checked="true"/>
<item android:drawable="#drawable/uncked_checkbox"/>
</selector>
If you use androidx.appcompat:appcompat and want a custom drawable (of type selector with android:state_checked) to work on old platform versions in addition to new platform versions, you need to use
<CheckBox
app:buttonCompat="#drawable/..."
instead of
<CheckBox
android:button="#drawable/..."
Adding custom drawable in the android:button did not work for me in Material Checkbox version-1.3.0 . I had to set android:drawable="#drawable/checkbox_selector" instead and also set android:button="#null" . You can also add android:drawablePadding to make it look good. However, this makes the entire checkbox clickable (along with the text).

Categories

Resources