Android color selector with radio buttons - android

I would like to create a group of radio buttons to pick a color. Something like this:
How can I achieve something like this? I didn't find any color property on the original RadioButton. Do I have to create a custom control? If yes, can someone just hint me on the basic steps so I can try to some new research? I'm very new to Android, and trying to learn by doing...

You can surely try custom radio buttons or you could simply use or inflate views to achieve this kind of color picker.
with xml: you will need to create two drawable resource files in the drawable folder. First goes like this,
<shape xmlns:android="http://schemas.android.com/apk/res/android"
android:shape="oval">
<solid android:color="#e91e63" />
<size
android:width="48dp"
android:height="48dp" />
This is applicable when you haven't received any click on the view (clickable). The second file applies when we detect a click.
xmlns:android="http://schemas.android.com/apk/res/android"
android:shape="oval">
<solid android:color="#e91e63" />
<size
android:width="53dp"
android:height="53dp" />
<stroke
android:width="5dp"
android:color="#d2d1d2" />
Now, in the activity one needs to set the background drawable to the view (be it image button or imageview). This goes like this (just an example):
public class MainActivity extends AppCompatActivity {
private ImageButton img;
private boolean isSelected = false;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
img = (ImageButton) findViewById(R.id.img);
img.setClickable(true);
img.setBackground(getDrawable(R.drawable.unselected_circle));
img.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
img.startAnimation(AnimationUtils.loadAnimation(getBaseContext(), android.R.anim.fade_in));
if (isSelected) {
isSelected = false;
img.setBackground(getDrawable(R.drawable.unselected_circle));
} else {
isSelected = true;
img.setBackground(getDrawable(R.drawable.selected_circle));
}
}
});
}
}
and the activity_main layout looks something like this:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="#+id/viewGroup"
tools:context="com.android.empty.MainActivity">
<ImageButton
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:padding="10dp"
android:layout_margin="20dp"
android:clickable="true"
android:id="#+id/img"/>
However, with this method one will end up creating multiple drawables for different colors. To avoid that, we can create the drawables programmatically, writing code once and using the same for different colors using setColor(int color) method:
public class MainActivity extends AppCompatActivity {
private ImageButton img;
private boolean isSelected = false;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final GradientDrawable unselected = new GradientDrawable();
unselected.setShape(GradientDrawable.OVAL);
unselected.setColor(Color.parseColor("#e91e63"));
unselected.setSize(144, 144);
final GradientDrawable selected = new GradientDrawable();
selected.setShape(GradientDrawable.OVAL);
selected.setColor(Color.parseColor("#E91E63"));
selected.setSize(159, 159);
selected.setStroke(15, Color.parseColor("#D2D1D2"));
img = (ImageButton) findViewById(R.id.img);
img.setBackground(unselected);
img.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
img.startAnimation(AnimationUtils.loadAnimation(getBaseContext(), android.R.anim.fade_in));
if (isSelected) {
isSelected = false;
img.setBackground(unselected);
} else {
isSelected = true;
img.setBackground(selected);
}
}
});
}
}
The result looks something like this
Note: This example tells only the way to achieve one selector like the one mentioned in the question. To create multiple selectors, one needs to inflate the view (Image Button) using LayoutInflater class.

I Was stuck in the same problem to use radio buttons but then I tried my own hand on and created [CustomRadioShapes]1 Lib.
Simple implementation.
implementation:
Download release aar file from CustomRadioAndShapes/library folder
In your Android Studio File-> New -> New Module -> Import .aar or .jar
Select aar file and SubProject Name as CustomRadioAndShapes. Done.

Replace Drawable in RadioButton
I found a way to use the native RadioButton. You have to create your own Drawable and Style and then you're good to go. It took me all afternoon to get it right, so dear poor soul reading this - I hope it helps.
Below is a list of all resources you would need to achieve the following:
Built on Android 13 (API level 33)
Tested to also work on Android 7.0 (API level 24)
drawable/colour_picker.xml
(start with the selector element if you don't care about the ripple effect when picking an option)
<?xml version="1.0" encoding="utf-8"?>
<ripple xmlns:android="http://schemas.android.com/apk/res/android"
android:color="#android:color/white" android:radius="50dp">
<item>
<selector>
<item android:drawable="#drawable/colour_picker_checked" android:state_checked="true" />
<item android:drawable="#drawable/colour_picker_unchecked" android:state_checked="false" />
</selector>
</item>
</ripple>
drawable/colour_picker_checked.xml
(make sure shapes only use tint instead of color here or they will later on be broken)
<?xml version="1.0" encoding="utf-8"?>
<layer-list xmlns:android="http://schemas.android.com/apk/res/android">
<item>
<shape android:shape="oval" android:tint="#FFFFFF">
<stroke android:width="5dp" />
<solid android:color="#android:color/transparent" />
<size android:width="50dp" android:height="50dp"/>
</shape>
</item>
<item android:top="10dp" android:bottom="10dp" android:left="10dp" android:right="10dp">
<shape android:shape="oval" android:tint="#FFFFFF">
<solid android:width="1dp" />
</shape>
</item>
</layer-list>
drawable/colour_picker_unchecked.xml
(size needs to match colour_picker_checked.xml exactly or selecting options causes layout shift)
<?xml version="1.0" encoding="utf-8"?>
<layer-list xmlns:android="http://schemas.android.com/apk/res/android">
<item>
<shape android:shape="oval" android:tint="#FFFFFF">
<solid android:color="#android:color/transparent" />
<size android:width="50dp" android:height="50dp"/>
</shape>
</item>
<item android:top="10dp" android:bottom="10dp" android:left="10dp" android:right="10dp">
<shape android:shape="oval" android:tint="#FFFFFF">
<solid android:width="1dp" />
</shape>
</item>
</layer-list>
values/styles.xml
(the settings will distribute and align the buttons horizontally)
<style name="colour_picker"
parent="Base.Widget.AppCompat.CompoundButton.RadioButton">
<item name="android:button">#drawable/colour_picker</item>
<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">false</item>
<item name="android:backgroundDimEnabled">true</item>
<item name="android:layout_width">0dp</item>
<item name="android:layout_height">0dp</item>
<item name="android:gravity">center</item>
<item name="android:layout_weight">1</item>
</style>
layout/colour_picker.xml
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:gravity="center"
android:layout_gravity="center"
android:orientation="vertical"
android:theme="#style/RippleStyle">
<RadioGroup
android:id="#+id/colour_choice"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="horizontal"
android:paddingBottom="10dp">
<RadioButton name="" style="#style/colour_picker" android:buttonTint="#FFFFFF"/>
<RadioButton style="#style/colour_picker" android:buttonTint="#FF00FF"/>
</RadioGroup>
</LinearLayout>
How to Use It
The only difficulty at this point is identifying which option was chosen. If your list of colours is fixed and you don't mind hardcoding, consider giving each RadioButton an android:id directly in the XML.
In my case, I chose to create the RadioButton objects programmatically, which lets me cross-reference the colour from a string-array resource.
String[] colourPalette = getResources().getStringArray(R.array.colour_options);
RadioGroup colourPicker = findViewById(R.id.YOUR_LAYOUT_WHERE_THIS_SHOULD_END_UP);
LayoutInflater inflater = LayoutInflater.from(this);
for (int i = 0; i < colourPalette.length; i++) {
RadioButton colourOption = (RadioButton) inflater.inflate(R.layout.colour_picker_item,null).getRootView();
colourOption.setId(i);
colourOption.setButtonTintList(ColorStateList.valueOf(Color.parseColor(colourPalette[i])));
colourPicker.addView(colourOption);
}
For this to work you need two additional resources:
layout/colour_picker_item.xml
<?xml version="1.0" encoding="utf-8"?>
<RadioButton style="#style/colour_picker" />
values/colors.xml
<string-array name="colour_options">
<item name="#FFFF00">#FFFF00</item>
<item name="#FF0000">#FF0000</item>
</string-array>
And then in your code it's as easy as this:
colourPicker.setOnCheckedChangeListener((group, checkedId) -> {
RadioButton colourOption = colourPicker.findViewById(checkedId);
int colour = Color.parseColor(colourPalette[colourOption.getId()]);
// do whatever you need to do with your picked colour
});

Related

Customized circular checkbox in Android

I am trying to get the Google apps photo select UI .. Am using Appcompat checkbox to achieve that with out success. The steps I am working on ,
1. Set the checkbox background to custom circular shape
2. define custom shape in xml
This is my check box xml looks like ,
<android.support.v7.widget.AppCompatCheckBox
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/checkBox"
android:layout_alignParentTop="true"
android:layout_alignParentLeft="true"
android:button="#drawable/custom_checkbox"
android:background="#drawable/checkbox_drawable"
/>
My custom checkbox background,
<shape xmlns:android="http://schemas.android.com/apk/res/android"
android:shape="oval">
<stroke
android:width="1dp"
android:color="#78d9ff"/>
<solid
android:color="#79bfea"/>
</shape>
My checkbox button ,
<selector>
<item android:drawable="#drawable/checkbox_drawable"
android:state_checked="false"/>
<item android:drawable="#drawable/selected_check"
android:state_checked="true"/>
</selector>
I even changed from android:background to android:button .. nothing gives me the circular check box .. Any help is appreciated ? Should I use floating action bar ? or a view ? Any suggestions ?
Custom Checkbox with two drawable image.
1. In .xml file
<android.support.v7.widget.AppCompatCheckBox
android:id="#+id/checkBox"
android:layout_width="40dp"
android:layout_height="40dp"
android:layout_gravity="center"
android:background="#drawable/checkbox_selector"
android:button="#color/white"
android:checked="true" />
2. Create checkbox_selector.xml in drawable folder.
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:drawable="#drawable/cancel"
android:state_checked="false"/>
<item android:drawable="#drawable/checked"
android:state_checked="true"/>
</selector>
3. Add checked.png and cansel.phd image in drawable folder from the below link
https://icons8.com/icon/set/yes/all
And
https://icons8.com/icon/set/cross/all
4. Checkbox click event
AppCompatCheckBox checkBox = (AppCompatCheckBox) view.findViewById(R.id.checkBox);
checkBox.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (checkBox.isChecked()){
checkBox.setChecked(false);
}else {
checkBox.setChecked(true);
}
}
});
You need to give size to your drawable when you want to use it for button attribute.
<shape xmlns:android="http://schemas.android.com/apk/res/android" android:shape="oval">
<stroke
android:width="1dp"
android:color="#78d9ff"/>
<solid android:color="#79bfea"/>
<size
android:width="20dp"
android:height="20dp"/>
</shape>
And apply to CheckBox with android:button.
Also since this is a checkbox, you should use selector to have checked and unchecked state.
An example of selector is
<selector xmlns:android="http://schemas.android.com/apk/res/android" >
<item android:drawable="#drawable/normal"
android:state_checked="false"/>
<item android:drawable="#drawable/checked"
android:state_checked="true"/>
<item android:drawable="#drawable/normal"/>
</selector>
You may not be looking now, however i have code which seems to make circular image with checkbox please have a look at my answer given on another thread.
Click here to view answer on another thread
check my answer on the question in the link, with that you will be able to create and customise your checkbox without the need of coding
answer here
Create a custom checkbox background
custom_check_box_background.xml
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:drawable="#drawable/ic_unchecked_check_box_background"
android:state_checked="false"/>
<item android:drawable="#drawable/ic_checked_check_box_background"
android:state_checked="true"/>
</selector>
After this go to the checkbox and call this xml file from the checkbox
<androidx.appcompat.widget.AppCompatCheckBox
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:checked="true"
android:button="#drawable/custom_check_box_background"
android:gravity="center" />
This will allow you to switch the icons based on the status of checkbox.
Note: You can add your own drawable as background to obtain your desired shape.

"paddingLeft" disapears when I use setText() + setBackgroundDrawable() on a Button

I have this Button :
<Button
android:id="#+id/btStatSerie"
style="#style/ButtonPopUp"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginBottom="15dp"
android:text="#string/start_serie" />
Which call this style
<style name="ButtonPopUp" parent="ParentTheme">
<item name="android:background">#drawable/bt_menu_principal</item>
<item name="android:textColor">#color/white</item>
<item name="android:textStyle">bold</item>
<item name="android:textSize">15sp</item>
<item name="android:paddingLeft">15dp</item>
<item name="android:textAllCaps">true</item>
<item name="android:drawableRight">#drawable/ic_flche_blanche_bas</item>
<item name="android:gravity">left|center_vertical</item>
</style>
I set the text using setText() and at the same time setBackgroundDrawable() to express the change clearly to the user.
This remove the paddingLeft the style is providing.
Any ideas to solve this issue except writing a line under every setBackground() to set a padding from the code ?
And most important to me, WHY is this happening ?
ty
Edit : xml drawable :
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:drawable="#drawable/bt_border_pressed"
android:state_pressed="true" />
<item android:drawable="#drawable/bt_border_focused"
android:state_focused="true" />
<item android:drawable="#drawable/bt_border" />
where bt_border and Cie. looks like with only color modifications :
<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android">
<stroke
android:width="2dp"
android:color="#color/blue" />
<solid android:color="#color/blue" />
<padding
android:bottom="5dp"
android:left="5dp"
android:right="5dp"
android:top="5dp" />
<corners android:radius="7dp" />
</shape>
The new background I set (using setBackgroundResource() now) is also following the above modele (no selector). The padding is there when the screen is displayed for teh first time so really it is linked somehow to changing the background. Also, this issue was there before I start using a selector as xml drawable.
I think the problem lies within the fact that the default Button drawable contains paddings by default. The new drawable your setting probably does not have this padding and therefor padding disappears.
For example the default button drawable for ICS consists of a set of nine-patch images. Those nine-patch images contain padding.
Posting some source code of the drawable you're using could help!
You must set paddings after calling setBackgroundDrawable() method.
You can make a class extends Button, and override the setBackgroundDrawable(Drawable drawable) method, like this:
#Override
public void setBackgroundDrawable(Drawable drawable) {
int l = getPaddingLeft();
int t = getPaddingTop();
int r = getPaddingRight();
int b = getPaddingBottom();
super.setBackgroundDrawable(drawable);
setPadding(l, t, r, b);
}
Then replace your Button tag with this custom class

Android L FAB Button shadow

In the Material Design guidelines Google presented a new style of button, the FAB Button. I found instructions how to make it but I have trouble adding the shadow. How can this be achieved?
Check out the "activity.java", there is probably the code you need.
I made the Fab - Button like this:
layout.xml
<Button
style="?android:attr/buttonStyleSmall"
android:layout_width="56dp"
android:layout_height="56dp"
android:text="+"
android:textSize="40sp"
android:background="#drawable/ripple"
android:id="#+id/fabbutton"
android:layout_margin="#dimen/activity_horizontal_margin"
android:elevation="3dp"
android:paddingBottom="16dp"
android:fontFamily="sans-serif-light"
android:layout_alignParentEnd="true"
android:layout_gravity="right|bottom" />
ripple.xml
<?xml version="1.0" encoding="utf-8"?>
<ripple android:color="#ffb300" xmlns:android="http://schemas.android.com/apk/res/android">
<item android:drawable="#drawable/fab"></item>
</ripple>
fab.xml
<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android" android:shape="rectangle">
<solid android:color="#color/accentColor" />
</shape>
Activity.java
import android.graphics.Outline;
...
Button fab = (Button) rootView.findViewById(R.id.fabbutton);
Outline mOutlineCircle;
int shapeSize = getResources().getDimensionPixelSize(R.dimen.shape_size);
mOutlineCircle = new Outline();
mOutlineCircle.setRoundRect(0, 0, shapeSize, shapeSize, shapeSize / 2);
fab.setOutline(mOutlineCircle);
fab.setClipToOutline(true);
This code will be shown as error in android studio v0.8.1, so as other android l components. It will be fixed in the next version.
Result:
You can use a Button:
<ImageButton
android:id="#+id/fab"
android:background="#drawable/ripple"
android:stateListAnimator="#anim/anim"
android:src="#drawable/ic_action_add"
android:elevation="4dp"
/>
where the ic_action_add is your icon.
drawable/ripple.xml is:
<ripple xmlns:android="http://schemas.android.com/apk/res/android" android:color="?android:colorControlHighlight">
<item>
<shape android:shape="oval">
<solid android:color="?android:colorAccent" />
</shape>
</item>
</ripple>
anim/anim.xml is:
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item
android:state_enabled="true"
android:state_pressed="true">
<objectAnimator
android:duration="#android:integer/config_shortAnimTime"
android:propertyName="translationZ"
android:valueFrom="#dimen/button_elevation"
android:valueTo="#dimen/button_press_elevation"
android:valueType="floatType" />
</item>
<item>
<objectAnimator
android:duration="#android:integer/config_shortAnimTime"
android:propertyName="translationZ"
android:valueFrom="#dimen/button_press_elevation"
android:valueTo="#dimen/button_elevation"
android:valueType="floatType" />
</item>
</selector>
Dimens.xml is
<resources>
<dimen name="fab_size">56dp</dimen>
<dimen name="button_elevation">2dp</dimen>
<dimen name="button_press_elevation">4dp</dimen>
</resources>
With the elevation attribute you should set the Outline via code:
public class MainActivity extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.layoutfab);
//Outline
Button fab = (Button) findViewById(R.id.fab)
ViewOutlineProvider viewOutlineProvider = new ViewOutlineProvider() {
#Override
public void getOutline(View view, Outline outline) {
// Or read size directly from the view's width/height
int size = getResources().getDimensionPixelSize(R.dimen.fab_size);
outline.setOval(0, 0, size, size);
}
};
fab.setOutlineProvider(viewOutlineProvider);
}
}
The problem with the circular shadow can be easily solved without any tricks with Outline: just add these properties to the button in the XML layout (in addition to the custom background):
android:elevation="5dp"
android:stateListAnimator="#null"
Although Android Studio may display it wrong in the layout preview, it works fine when launched on a device.

Android highlight an imagebutton when clicked

I am using an ImageButton. But I don get the highlight when clicked. I googled and many suggested to use selector where another image is displayed. Is there any way around this. by using only one image and highlighting it or giving it a glow effect. so that the user knows that button has been clicked.
This is actually not very difficult to do. You don't even need to create 2 seperate .png files or anything like that. For instance, if you want to have a button which has a gradient, and then change it when the button is pressed:
Step 1:
Create default button gradient (drawable/default_button.xml):
<shape xmlns:android="http://schemas.android.com/apk/res/android"
android:shape="rectangle">
<corners android:radius="3dp" />
<gradient android:endColor="#8ba0bb" android:startColor="#43708f" android:angle="90" />
<stroke android:width="1dp" android:color="#33364252" />
</shape>
Step 2: Create default button pressed gradient (drawable/default_button_pressed.xml):
<shape xmlns:android="http://schemas.android.com/apk/res/android"
android:shape="rectangle">
<corners android:radius="3dp" />
<gradient android:endColor="#43708f" android:startColor="#8ba0bb" android:angle="90" />
<stroke android:width="1dp" android:color="#33364252" />
</shape>
Step 3: Create selector (drawable/default_button_selector.xml):
<selector xmlns:android="http://schemas.android.com/apk/res/android" >
<item android:state_pressed="true" android:drawable="#drawable/default_button_pressed" />
<item android:drawable="#drawable/default_button" />
</selector>
Step 4 (optional): Create style for the button (values/style.xml):
<resources>
<style name="DefaultButton">
<item name="android:layout_width">wrap_content</item>
<item name="android:layout_height">wrap_content</item>
<item name="android:background">#drawable/default_button_selector</item>
</style>
</resources>
Step 5: use the button (layout/main.xml):
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent" android:layout_height="fill_parent">
<button style="#style/DefaultButton" />
</RelativeLayout>
As you can see, it's not particularly difficult to do.
Without having to create multiple images (pressed, normal etc) and even don't have to create selector. Use setOnTouchListener rather than setOnClickListener. The below code will give you the grey overlay on the clicked item.
((ImageButton)findViewById(R.id.myImageBtn)).setOnTouchListener(new OnTouchListener() {
#Override
public boolean onTouch(View v, MotionEvent event) {
switch (event.getAction()) {
case MotionEvent.ACTION_DOWN: {
ImageButton view = (ImageButton ) v;
view.getBackground().setColorFilter(0x77000000, PorterDuff.Mode.SRC_ATOP);
v.invalidate();
break;
}
case MotionEvent.ACTION_UP:
// Your action here on button click
case MotionEvent.ACTION_CANCEL: {
ImageButton view = (ImageButton) v;
view.getBackground().clearColorFilter();
view.invalidate();
break;
}
}
return true;
}
});
You can simply use android:foreground for your View to achieve clickable effect:
android:foreground="?android:attr/selectableItemBackground"
For use with dark theme add also theme to your layout (to make clickable effect clear):
android:theme="#android:style/ThemeOverlay.Material.Dark"
In order not to have to set several drawable for each button I set the color filter attribute of the image button in an on touch listener.
See code here in another post:
https://stackoverflow.com/a/14278790/891479
I managed to do this!!
First you declare buttonStyle.xml in drawable folder.
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item
android:state_focused="true"
android:state_pressed="true"
android:drawable="#drawable/button_pressed" />
<item
android:state_focused="false"
android:state_pressed="true"
android:drawable="#drawable/button_pressed" />
<item android:drawable="#drawable/button_normal" />
</selector>
Then you create button_pressed.xml in drawable folder.
<?xml version="1.0" encoding="UTF-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
android:shape="rectangle" >
<solid android:color="#color/semiTransparentGnfrBlueColor" />
<stroke android:width="10dp" android:color="#android:color/transparent" />
</shape>
After that, you create button_normal.xml in drawable folder.
<?xml version="1.0" encoding="UTF-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
android:innerRadiusRatio="3"
android:shape="rectangle">
<solid android:color="#color/gnfrBlueColor"/>
<stroke android:width="10dp" android:color="#android:color/transparent" />
</shape>
You can use default colors but if you want to do it like me, you need to have a file named colors.xml in values folder and this values inside:
<?xml version="1.0" encoding="utf-8"?>
<resources>
<item name="gnfrBlueColor" type="color">#2A3748</item>
<item name="semiTransparentGnfrBlueColor" type="color">#602A3748</item>
<integer-array name="androidcolors">
<item>#color/gnfrBlueColor</item>
<item>#color/semiTransparentGnfrBlueColor</item>
</integer-array>
</resources>
Finally you set this to your button or whatever:
savedAccountLoginButton.SetBackgroundResource(Resource.Drawable.buttonStyle);
NOTICE THAT I set a stroke with color transparent because when you set backgroundresource your button becomes bigger and with this trick it remains original.
This is the only way I could archieve this programmatically.
If you want to do this by XML:
<Button
android:text="ENTRAR"
android:layout_width="match_parent"
android:layout_height="60dp"
android:background="#drawable/buttonstyle"
android:textColor="#color/white"
android:textSize="18sp"
android:id="#+id/button1" />

How to Change color of Button in Android when Clicked?

I am working on Android Application. I want to have 4 buttons to be placed horizontally at the bottom of the screen. In these 4 buttons 2 buttons are having images on them. The border of the buttons should be black color and the border should be as thin as possible. When I click the button, I want the background of the button should be changed to blue color without the color of border to be changed and should be remained in that color for some time. How can I achieve this scenario in Android?
One approach is to create an XML file like this in drawable, called whatever.xml:
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item
android:state_focused="true"
android:state_pressed="true"
android:drawable="#drawable/bgalt" />
<item
android:state_focused="false"
android:state_pressed="true"
android:drawable="#drawable/bgalt" />
<item android:drawable="#drawable/bgnorm" />
</selector>
bgalt and bgnormare PNG images in drawable.
If you create the buttons programatically in your activity, you can set the background with:
final Button b = new Button (MyClass.this);
b.setBackgroundDrawable(getResources().getDrawable(R.drawable.whatever));
If you set your buttons' style with an XML, you would do something like:
<Button
android:id="#+id/mybutton"
android:background="#drawable/watever" />
And finally a link to a tutorial.
Save this code in drawable folder with "bg_button.xml" and call "#drawable/bg_button" as background of button in your xml:
<?xml version="1.0" encoding="UTF-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:state_pressed="true" >
<shape>
<solid
android:color="#004F81" />
<stroke
android:width="1dp"
android:color="#222222" />
<corners
android:radius="7dp" />
<padding
android:left="10dp"
android:top="10dp"
android:right="10dp"
android:bottom="10dp" />
</shape>
</item>
<item>
<shape>
<gradient
android:startColor="#89cbee"
android:endColor="#004F81"
android:angle="270" />
<stroke
android:width="1dp"
android:color="#4aa5d4" />
<corners
android:radius="7dp" />
<padding
android:left="10dp"
android:top="10dp"
android:right="10dp"
android:bottom="10dp" />
</shape>
</item>
</selector>
Try This
final Button button = (Button) findViewById(R.id.button_id);
button.setOnTouchListener(new View.OnTouchListener() {
#Override
public boolean onTouch(View view, MotionEvent event) {
if(event.getAction() == MotionEvent.ACTION_UP) {
button.setBackgroundColor(Color.RED);
} else if(event.getAction() == MotionEvent.ACTION_DOWN) {
button.setBackgroundColor(Color.BLUE);
}
return false;
}
});
Refer this,
boolean check = false;
Button backward_img;
Button backward_img1;
backward_img = (Button) findViewById(R.id.bars_footer_backward);
backward_img1 = (Button) findViewById(R.id.bars_footer_backward1);
backward_img.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
check = true;
backward_img.setBackgroundColor(Color.BLUE);
}
});
if (check == true) {
backward_img1.setBackgroundColor(Color.RED);
backward_img.setBackgroundColor(Color.BLUE);
}
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<!-- default -->
<item
android:state_pressed="false"
android:state_focused="false">
<shape
android:innerRadiusRatio="1"
android:shape="rectangle" >
<solid android:color="#00a3e2" />
<padding
android:bottom="10dp"
android:left="10dp"
android:right="10dp"
android:top="10dp" />
</shape>
</item>
<!-- button focused -->
<item
android:state_pressed="false"
android:state_focused="true">
<shape
android:innerRadiusRatio="1"
android:shape="rectangle" >
<solid android:color="#5a97f5" />
<padding
android:bottom="5dp"
android:left="10dp"
android:right="10dp"
android:top="5dp" />
</shape></item>
<!-- button pressed -->
<item
android:state_pressed="true"
android:state_focused="false">
<shape
android:innerRadiusRatio="1"
android:shape="rectangle" >
<solid android:color="#478df9"/>
<padding
android:bottom="10dp"
android:left="10dp"
android:right="10dp"
android:top="10dp" />
</shape></item>
</selector>
If you want to change the backgorund image or color of the button when it is pressed, then just copy this code and paste in your project at exact location described below.
<!-- Create new xml file like mybtn_layout.xml file in drawable -->
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:state_pressed="true" android:drawable="#drawable/pressed" /> <!--pressed -->
<item android:drawable="#drawable/normal" /> <!-- Normal -->
</selector>
<!-- Now this file should be in a drawable folder and use this
single line code in button code to get all the properties of this xml file -->
<Button
android:id="#+id/street_btn"
android:layout_width="wrap_content"
android:background="#drawable/layout_a" > <!-- your required code -->
</Button>
1-make 1 shape for Button
right click on drawable nd new drawable resource file .
change Root element to shape and make your shape.
enter image description here
2-now make 1 copy from your shape and change name and change solid color.
enter image description here
3-right click on drawable and new drawable resource file
just set root element to selector.
go to file and set "state_pressed"
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:state_pressed="true"android:drawable="#drawable/YourShape1"/>
<item android:state_pressed="false" android:drawable="#drawable/YourShape2"/>
</selector>
4-the end go to xml layout and set your Button background "your selector"
(sorry for my english weak)
Try this......
First create an xml file named button_pressed.xml
These are it's contents.
<?xml version="1.0" encoding="utf-8"?>
<selector
xmlns:android="http://schemas.android.com/apk/res/android">
<item android:state_focused="true"
android:state_pressed="false"
android:drawable="#drawable/icon_1" />
<item android:state_focused="true"
android:state_pressed="true"
android:drawable="#drawable/icon_1_press" />
<item android:state_focused="false"
android:state_pressed="true"
android:drawable="#drawable/icon_1_press" />
<item android:drawable="#drawable/icon_1" />
</selector>
Noe try this on your button.
int imgID = getResources().getIdentifier("button_pressed", "drawable", getApplication().getPackageName());
button.setImageResource(imgID);
button_pressed.xml should be in the drawable folder.
icon_1_press and icon_1 are two images for button press and normal focus.
you can try this code to solve your problem
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:state_pressed="true"
android:drawable="#drawable/login_selected" /> <!-- pressed -->
<item android:state_focused="true"
android:drawable="#drawable/login_mouse_over" /> <!-- focused -->
<item android:drawable="#drawable/login" /> <!-- default -->
</selector>
write this code in your drawable make a new resource and name it what you want and then write the name of this drwable in the button same as we refer to image src in android
I am use this code (with ripple effect):
<ripple xmlns:android="http://schemas.android.com/apk/res/android" android:color="#color/color_gray">
<item android:id="#android:id/mask">
<color android:color="#color/color_gray" />
</item></ripple>
public void onPressed(Button button, int drawable) {
if (!isPressed) {
button.setBackgroundResource(R.drawable.bg_circle);
isPressed = true;
} else {
button.setBackgroundResource(drawable);
isPressed = false;
}
}
#Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.circle1:
onPressed(circle1, R.drawable.bg_circle_gradient);
break;
case R.id.circle2:
onPressed(circle2, R.drawable.bg_circle2_gradient);
break;
case R.id.circle3:
onPressed(circle3, R.drawable.bg_circle_gradient3);
break;
case R.id.circle4:
onPressed(circle4, R.drawable.bg_circle4_gradient);
break;
case R.id.circle5:
onPressed(circle5, R.drawable.bg_circle5_gradient);
break;
case R.id.circle6:
onPressed(circle6, R.drawable.bg_circle_gradient);
break;
case R.id.circle7:
onPressed(circle7, R.drawable.bg_circle4_gradient);
break;
}
please try this, in this code i m trying to change the background of button on button click this works fine.
To deal properly for how long you want to have your button stay in your other color I would advise this version:
button.setOnTouchListener(new View.OnTouchListener() {
#Override
public boolean onTouch(View v, MotionEvent event) {
switch(event.getAction()) {
case MotionEvent.ACTION_DOWN:
button.setBackground(getResources().getDrawable(R.drawable.on_click_drawable));
break;
case MotionEvent.ACTION_UP:
new java.util.Timer().schedule(
new java.util.TimerTask() {
#Override
public void run() {
((Activity) (getContext())).runOnUiThread(new Runnable() {
#Override
public void run() {
button.setBackground(getResources().getDrawable(R.drawable.not_clicked_drawable));
}
});
}
}, BUTTON_CLICK_TIME_AFTER_RELEASE_ANIMATION);
break;
default:
}
return false;
}
});
BUTTON_CLICK_TIME_AFTER_RELEASE_ANIMATION indicates after how much time [ms] the button will reset to the previous state (however you might want to use some boolean to check that the button hadn't been used in between, depending on what you want to achieve...).
Even using some of the comments above this took way longer to work out that should be necessary. Hopefully this example helps someone else.
Create a radio_button.xml in the drawable directory.
<?xml version="1.0" encoding="utf-8"?>
<!-- An element which allows two drawable items to be listed.-->
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:state_checked="true" android:drawable="#drawable/radio_button_checked" /> <!--pressed -->
<item android:drawable="#drawable/radio_button_unchecked" /> <!-- Normal -->
</selector>
Then in the xml for the fragment should look something like
<?xml version="1.0" encoding="utf-8"?>
<layout xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools">
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical">
<RadioGroup
android:layout_width="match_parent"
android:layout_height="match_parent">
<RadioButton
android:id="#+id/radioButton1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginLeft="10dp"
android:layout_weight="1"
android:button="#drawable/radio_button"
android:paddingLeft="10dp" />
<RadioButton
android:id="#+id/radioButton2"
android:layout_marginLeft="10dp"
android:paddingLeft="10dp"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_weight="1"
android:button="#drawable/radio_button" />
</RadioGroup>
</LinearLayout>
</layout>
Just add 1 line in XML for the click item
android:background="?android:attr/selectableItemBackground"
hai the most easiest way is this:
add this code to mainactivity.java
public void start(View view) {
stop.setBackgroundResource(R.color.red);
start.setBackgroundResource(R.color.yellow);
}
public void stop(View view) {
stop.setBackgroundResource(R.color.yellow);
start.setBackgroundResource(R.color.red);
}
and then in your activity main
<button android:id="#+id/start" android:layout_height="wrap_content" android:layout_width="wrap_content" android:onclick="start" android:text="Click">
</button><button android:id="#+id/stop" android:layout_height="wrap_content" android:layout_width="wrap_content" android:onclick="stop" android:text="Click">
or follow along this tutorial

Categories

Resources