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;
}
}
Related
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-desired-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());
I have a TextView, I want to change its color by clicking it and save after exiting app, I used selector tag in a xml file in drawable folder but the problem is default color is right but nothing happens on click why?
Selector xml:
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:state_pressed="true" android:color="#FFA500"/>
<item android:color="#FF0000"/>
</selector>
TextView xml:
<TextView
android:id="#+id/textView2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="35dp"
android:text="Transferef Money"
android:textAppearance="?android:attr/textAppearanceSmall"
android:textColor="#drawable/selector" />
While color can be changed through a click handler
TextView textView = new TextView(this);
textView.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
textView.setTextColor(Color.BLACK);
}
});
add an onClick attribute to your XML
<TextView
android:id="#+id/textView2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="35dp"
android:text="Transferef Money"
android:textAppearance="?android:attr/textAppearanceSmall"
android:textColor="#drawable/selector"
android:onClick="colorise"
/>
and then set the color in colorise method.
Also, I don't think the state will be saved via an XML file, so you will have to handle it programitically.
You could avoid the XML completely and focus on it in your Java activity class:
TextView lbl = (TextView)findViewById(R.id.myTextView);
lbl.setOnClickListener (new View.OnClickListener()
{
public void onClick(View v)
{
TextView lbl = (TextView)findViewById(R.id.myTextView);
lbl.setTextColor(Color.parseColor("#FF0000"));
lbl.setTextColor(Color.rgb(int, int, int));
lbl.setTextColor(Color.RED);
}
});
First define color in colors.xml, and use them in your selector, this works well for me.
Example:
<item android:state_focused="true" android:color="#color/blue_2"/>
<item android:state_pressed="true" android:color="#color/blue_2"/>
<item android:state_checked="true" android:color="#color/blue_2"/>
<item android:color="#color/black_1"/>
Is it possible to change rectangle (drawn in xml) color in Java code while app is running?
My rectangle.xml:
<?xml version="1.0" encoding="UTF-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android" android:id="#+id/listview_background_shape">
<stroke android:width="2dp" android:color="#ffffff" />
<padding android:left="20dp"
android:top="20dp"
android:right="20dp"
android:bottom="20dp" />
<solid android:color="#006600" />
</shape>
Drawn in main.xml by:
<View
android:id="#+id/myRectangleView"
android:layout_width="wrap_content"
android:layout_height="100dp"
android:background="#drawable/rectangle"/>
I've tried this way:
GradientDrawable sd;
View viewrectangle;
viewrectangle = (View) findViewById(R.id.myRectangleView);
sd = (GradientDrawable) viewrectangle.getBackground();
sd.setColor(0xffffff00);
sd.invalidateSelf();
It only works when I put it inside OnCreate method.
I want to change rect color by a button, so I put this code inside button's onClick() method. But when I click button while app is running color doesn't change. Any suggestions?
Used this code and it worked, alternatively consider redrawing the viewrectangle using viewrectangle.invalidate(), but it shouldn't be nescarry:
View viewrectangle;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
viewrectangle = (View) findViewById(R.id.myRectangleView);
}
public void doClick(View v) {
GradientDrawable sd = (GradientDrawable) viewrectangle.getBackground();
sd.setColor(0xffffff00);
sd.invalidateSelf();
}
In this example the "doClick()" method is set in the main.xml:
<Button android:layout_height="wrap_content"
android:layout_width="match_parent"
android:text="Button"
android:onClick="doClick"/>
You can put this code in a separate method, and that method you can call from onClick of button..
You could try a color filter. I've used it before to change the color of buttons (note that they started out as standard gray), if you start with another color it could be a very different outcome. Anyway, an example of how I did it:
Import the PorterDuff graphics stuff:
import android.graphics.PorterDuff;
In the class define the item you want to color filter and set the filter:
Button atdButton = (Button) convertView.findViewById(R.id.attendbutton);
if (atdState[position].equals("P")) {
atdButton.getBackground().setColorFilter(0xFF00FF00, // Set filter to green
PorterDuff.Mode.MULTIPLY);
} else if (atdState[position].equals("T")) {
atdButton.getBackground().setColorFilter(0xFFFFFF00, // Set filter to yellow
PorterDuff.Mode.MULTIPLY);
} else if (atdState[position].equals("E")) {
atdButton.getBackground().setColorFilter(0xFFFF6600, // Set filter to orange
PorterDuff.Mode.MULTIPLY);
} else if (atdState[position].equals("U")) {
atdButton.getBackground().setColorFilter(0xFFFF0000, // Set filter to red
PorterDuff.Mode.MULTIPLY);
} else {
atdButton.getBackground().clearColorFilter();
}
In Android, when I set a background image to a button, I can not see any effect on it when it's clicked.
I need to set some effect on the button, so the user can recognise that the button is clicked.
The button should be dark for a few seconds when it is clicked. How to do this?
This can be achieved by creating a drawable xml file containing a list of states for the button. So for example if you create a new xml file called "button.xml" with the following code:
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:state_focused="true" android:state_pressed="false" android:drawable="#drawable/YOURIMAGE" />
<item android:state_focused="true" android:state_pressed="true" android:drawable="#drawable/gradient" />
<item android:state_focused="false" android:state_pressed="true" android:drawable="#drawable/gradient" />
<item android:drawable="#drawable/YOURIMAGE" />
</selector>
To keep the background image with a darkened appearance on press, create a second xml file and call it gradient.xml with the following code:
<?xml version="1.0" encoding="utf-8"?>
<layer-list xmlns:android="http://schemas.android.com/apk/res/android" >
<item>
<bitmap android:src="#drawable/YOURIMAGE"/>
</item>
<item>
<shape xmlns:android="http://schemas.android.com/apk/res/android">
<gradient android:angle="90" android:startColor="#880f0f10" android:centerColor="#880d0d0f" android:endColor="#885d5d5e"/>
</shape>
</item>
</layer-list>
In the xml of your button set the background to be the button xml e.g.
android:background="#drawable/button"
Changed the above code to show an image (YOURIMAGE) in the button as opposed to a block colour.
It is simpler when you have a lot of image buttons, and you don't want to write xml-s for every button.
Kotlin Version:
fun buttonEffect(button: View) {
button.setOnTouchListener { v, event ->
when (event.action) {
MotionEvent.ACTION_DOWN -> {
v.background.setColorFilter(-0x1f0b8adf, PorterDuff.Mode.SRC_ATOP)
v.invalidate()
}
MotionEvent.ACTION_UP -> {
v.background.clearColorFilter()
v.invalidate()
}
}
false
}
}
Java Version:
public static void buttonEffect(View button){
button.setOnTouchListener(new OnTouchListener() {
public boolean onTouch(View v, MotionEvent event) {
switch (event.getAction()) {
case MotionEvent.ACTION_DOWN: {
v.getBackground().setColorFilter(0xe0f47521,PorterDuff.Mode.SRC_ATOP);
v.invalidate();
break;
}
case MotionEvent.ACTION_UP: {
v.getBackground().clearColorFilter();
v.invalidate();
break;
}
}
return false;
}
});
}
Create your AlphaAnimation Object that decides how much will be the fading effect of the button, then let it start in the onClickListener of your buttons
For example :
private AlphaAnimation buttonClick = new AlphaAnimation(1F, 0.8F);
// some code
public void onClick(View v) {
v.startAnimation(buttonClick);
}
of course this is just a way, not the most preferred one, it's just easier
You can simply use 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 clickable effect be clear):
android:theme="#android:style/ThemeOverlay.Material.Dark"
To make your item consistent with the system look and feel try referencing the system attribute android:attr/selectableItemBackground in your desired view's background or foreground tag:
<ImageView
...
android:background="?android:attr/selectableItemBackground"
android:foreground="?android:attr/selectableItemBackground"
...
/>
Use both attributes to get desired effect before/after API level 23 respectively.
https://stackoverflow.com/a/11513474/4683601
Or using only one background image you can achive the click effect by using setOnTouchListener
Two ways
((Button)findViewById(R.id.testBth)).setOnTouchListener(new OnTouchListener() {
#Override
public boolean onTouch(View v, MotionEvent event) {
switch (event.getAction()) {
case MotionEvent.ACTION_DOWN: {
Button view = (Button) 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: {
Button view = (Button) v;
view.getBackground().clearColorFilter();
view.invalidate();
break;
}
}
return true;
}
});
And if you don't want to use setOnTouchLister, the another way of achieving this is
myButton.getBackground().setColorFilter(.setColorFilter(0xF00, Mode.MULTIPLY);
StateListDrawable listDrawable = new StateListDrawable();
listDrawable.addState(new int[] {android.R.attr.state_pressed}, drawablePressed);
listDrawable.addState(new int[] {android.R.attr.defaultValue}, myButton);
myButton.setBackgroundDrawable(listDrawable);
For all the views
android:background="?android:attr/selectableItemBackground"
But for cardview which has elevation use
android:foreground="?android:attr/selectableItemBackground"
For Circular click effect as in toolbar
android:background="?android:attr/actionBarItemBackground"
Also you need to set
android:clickable="true"
android:focusable="true"
This is the best solution I came up with taking hints from #Vinayak's answer. All the other solutions have different drawbacks.
First of all create a function like this.
void addClickEffect(View view)
{
Drawable drawableNormal = view.getBackground();
Drawable drawablePressed = view.getBackground().getConstantState().newDrawable();
drawablePressed.mutate();
drawablePressed.setColorFilter(Color.argb(50, 0, 0, 0), PorterDuff.Mode.SRC_ATOP);
StateListDrawable listDrawable = new StateListDrawable();
listDrawable.addState(new int[] {android.R.attr.state_pressed}, drawablePressed);
listDrawable.addState(new int[] {}, drawableNormal);
view.setBackground(listDrawable);
}
Explanation:
getConstantState().newDrawable() is used to clone the existing Drawable otherwise the same drawable will be used. Read more from here:
Android: Cloning a drawable in order to make a StateListDrawable with filters
mutate() is used to make the Drawable clone not share its state with other instances of Drawable. Read more about it here:
https://developer.android.com/reference/android/graphics/drawable/Drawable.html#mutate()
Usage:
You can pass any type of View (Button, ImageButton, View etc) as the parameter to the function and they will get the click effect applied to them.
addClickEffect(myButton);
addClickEffect(myImageButton);
just wanna add another easy way to do this: If your ImageButton remains its background and you don't set it to null, it will work like a normal button and will show the click animation while clicking exactly like other buttons.The way to hide the background while it is still there:
<ImageButton
android:id="#+id/imageButton2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:paddingBottom="1dp"
android:paddingLeft="1dp"
android:paddingRight="1dp"
android:paddingTop="1dp"
android:src="#drawable/squareicon" />
The paddings won't let the background be visible and make the button act like other buttons.
Step: set a button in XML with onClick Action:
<Button
android:id="#+id/btnEditUserInfo"
style="?android:borderlessButtonStyle"
android:layout_width="wrap_content"
android:layout_height="#dimen/txt_height"
android:layout_gravity="center"
android:background="#drawable/round_btn"
android:contentDescription="#string/image_view"
android:onClick="edit_user_info"
android:text="Edit"
android:textColor="#000"
android:textSize="#dimen/login_textSize" />
Step: on button clicked show animation point
//pgrm mark ---- ---- ----- ---- ---- ----- ---- ---- ----- ---- ---- -----
public void edit_user_info(View view) {
// show click effect on button pressed
final AlphaAnimation buttonClick = new AlphaAnimation(1F, 0.8F);
view.startAnimation(buttonClick);
Intent intent = new Intent(getApplicationContext(), EditUserInfo.class);
startActivity(intent);
}// end edit_user_info
I had the same issue, where I needed to have a transparent background but still get animation. Setting this solved it for me:
android:background="?android:selectableItemBackground"
Also this if you want to have circular effect:
android:background="?android:selectableItemBackgroundBorderless"
Use RippleDrawable for Material Design state pressed/clicked effect. In order to achieve this, create ripple item as an .xml under /drawable folder and use it in android:background for any views.
Effect for icon pressed/clicked, use circular ripple effect, for example:
<ripple xmlns:android="http://schemas.android.com/apk/res/android"
android:color="#android:color/darker_gray"
/>
Effect for view clicked with rectangle boundary, we can add ripple over the existing drawable like bellow:
<?xml version="1.0" encoding="utf-8"?>
<ripple xmlns:android="http://schemas.android.com/apk/res/android"
android:color="#000000">
<item android:drawable="#drawable/your_background_drawable"/>
</ripple>
Create bounce.xml file fo animation
LOCATION:
res->anim->bounce.xml
<?xml version="1.0" encoding="utf-8"?>
<set xmlns:android="http://schemas.android.com/apk/res/android">
<scale
android:duration="100"
android:fromXScale="0.9"
android:fromYScale="0.9"
android:pivotX="50%"
android:pivotY="50%"
android:toXScale="1.0"
android:toYScale="1.0" />
</set>
Add this line in onClick to initialize
final Animation myAnim = AnimationUtils.loadAnimation(this,R.anim.bounce);
button.startAnimation(myAnim);
You get the shrink effect in a button click.
Simple and easy way to set View click effect.
Method
public AlphaAnimation clickAnimation() {
return new AlphaAnimation(1F, 0.4F); // Change "0.4F" as per your recruitment.
}
Set in View
yourView.startAnimation(clickAnimation());
Making a minor addition to Andràs answer:
You can use postDelayed to make the color filter last for a small period of time to make it more noticeable:
#Override
public boolean onTouch(final View v, MotionEvent event) {
switch (event.getAction()) {
case MotionEvent.ACTION_DOWN: {
v.getBackground().setColorFilter(color, PorterDuff.Mode.SRC_ATOP);
v.invalidate();
break;
}
case MotionEvent.ACTION_UP: {
v.postDelayed(new Runnable() {
#Override
public void run() {
v.getBackground().clearColorFilter();
v.invalidate();
}
}, 100L);
break;
}
}
return false;
}
You can change the value of the delay 100L to suit your needs.
If you're using xml background instead of IMG, just remove this :
<item>
<bitmap android:src="#drawable/YOURIMAGE"/>
</item>
from the 1st answer that #Ljdawson gave us.
Is there a way to specify an alternative background image/color for a Button in the XML file that is going to be applied onClick, or do I have to do a Button.setBackground() in the onClickListener?
To change the image by using code:
public void onClick(View v) {
if(v.id == R.id.button_id) {
ButtonName.setImageResource(R.drawable.ImageName);
}
}
Or, using an XML file:
<?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>
In OnClick, just add this code:
ButtonName.setBackgroundDrawable(getResources().getDrawable(R.drawable.ImageName));
In the latest version of the SDK, you would use the setBackgroundResource method.
public void onClick(View v) {
if(v == ButtonName) {
ButtonName.setBackgroundResource(R.drawable.ImageResource);
}
}
public void methodOnClick(View view){
Button.setBackgroundResource(R.drawable.nameImage);
}
i recommend use button inside LinearLayout for adjust to size of Linear.
Try:
public void onclick(View v){
ImageView activity= (ImageView) findViewById(R.id.imageview1);
button1.setImageResource(R.drawable.buttonpressed);}
I used this to change the background for my button
button.setBackground(getResources().getDrawable(R.drawable.primary_button));
"button" is the variable holding my Button, and the image am setting in the background is primary_button