What I want is, When the RelativeLayout press state is active, I want the layout alpha to be 50% and when its not I need 100% alpha.
The following code doesn't seem to be working.
if (relativelayout.hasFocus()){
relativelayout.setAlpha(0.5f);
}
I tried setting the background of the relative layout to this
<?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/drawer_list_pressed" />
<item android:state_focused="false"
android:drawable="#drawable/drawer_list_normal" />
<item android:state_selected="true"
android:drawable="#drawable/drawer_list_pressed" />
</selector>
It is working on changing the background but not alpha of the contents.
after some thinking i found a solution
public void pressed(final View view){
view.setOnTouchListener(new View.OnTouchListener() {
#Override
public boolean onTouch(View v, MotionEvent event) {
if (event.getAction() == MotionEvent.ACTION_DOWN){
view.setAlpha(0.5f);
}
else {
view.setAlpha(1.0f);
}
return true;
}
});
}
I have a view class TintSelectorImageButton that applies a tint using DrawCompat::setTintList:
public class TintSelectorImageButton extends ImageButton{
// Actual resource values seem to be fairly large and positive, so -1 should be a safe sentinel
protected static final int NO_TINT = -1;
public TintSelectorImageButton(Context context, AttributeSet attrs){
super(context, attrs);
TypedArray args = context.obtainStyledAttributes(attrs, R.styleable.TintSelectorImageButton);
if(args.hasValue(R.styleable.TintSelectorImageButton_tintList)){
int colorStates = args.getResourceId(R.styleable.TintSelectorImageButton_tintList, NO_TINT);
if(colorStates != NO_TINT){
ColorStateList colorStateRes = ContextCompat.getColorStateList(context, colorStates);
Drawable wrappedDrawable = DrawableCompat.wrap(getDrawable().mutate());
DrawableCompat.setTintList(wrappedDrawable, colorStateRes);
setImageDrawable(wrappedDrawable);
}
}
args.recycle();
}
}
I am providing it a ColorStateList through the defined xml property that looks like this one:
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item
android:color="#color/sheet_toolbar_disabled"
android:state_enabled="false"/>
<item
android:color="#color/sheet_nav_clicked"
android:state_pressed="true"/>
<item
android:color="#color/sheet_toolbar_enabled"/>
</selector>
Unfortunately, the pressed state is not actually showing when I touch the button, but click events are being passed properly to the provided View.OnClickListener:
mPrevSheetButton.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View v){
showSheet(mPrevSheetUid);
}
});
To get things to work for now, I just took the image and colored it in an image editor and used this selector:
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item
android:drawable="#drawable/button_prev_light_blue"
android:state_pressed="true"/>
<item
android:drawable="#drawable/button_prev_disabled"
android:state_enabled="false"/>
<item
android:drawable="#drawable/button_prev"/>
</selector>
Oddly, the drawable selector reaches the "pressed" state without issue.
To make this work with a ColorStateList change the background of your ImageButton to ?android:attr/selectableItemBackground or ?android:attr/selectableItemBackgroundBorderless.
For example,
<ImageButton
android:id="#+id/imageButton"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:background="?android:attr/selectableItemBackgroundBorderless"
android:src="#drawable/button" />
my xml file
<LinearLayout
android:id="#+id/fragmentSelectorArea"
android:layout_width="fill_parent"
android:layout_height="#dimen/main_seletor_height"
android:layout_marginBottom="#dimen/main_seletor_margin_bottom"
android:background="#color/mainBtnBg" >
<ImageButton
android:id="#+id/myBtn"
android:layout_width="0dp"
android:layout_height="#dimen/main_btn_height"
android:layout_weight="1"
android:background="#drawable/btn_selector" />
</LinearyLayout>
btn_selector.xml
<item android:state_pressed="true"
android:drawable="#drawable/pressed_btn" />
<item android:state_focused="true"
android:drawable="#drawable/focused_btn" />
<item android:drawable="#drawable/nonselected_btn"/>
activity.java
ImageButton btn1 = (ImageButton) findViewById(R.id.myBtn);
OnClickListener btnListener = new OnClickListener() {
#Override
public void onClick(View btn) {
switch (btn.getId()) {
case R.id.myBtn:
mPager.setCurrentItem(0);
break;
...
default:
break;
}
}
};
btn1.setOnClickListener(btnListener);
I want to use effect when I clicked buttons.
normal(no focused), focused, pressed<-
But the state_focused is not working.
So I can't see focused effect.
Please help me..
add image.
I solved it.
button selector just two case. (pressed, non-pressed)
I overriding onPageChangeListener() in ViewPagerIndicator.
state_focused applied whenever the button is focused on using a dpad or the trackball. Views don't generally show a focused state when using touch.
You can use setonTouchListener to create an effect on the touch of your ImageButton like ...
myBtn.setOnTouchListener(new OnTouchListener() {
#Override
public boolean onTouch(View v, MotionEvent event) {
if(event.getAction() == MotionEvent.ACTION_DOWN)
myBtn.setImageResource(R.drawable.quit_yes_selected);
else if(event.getAction() == MotionEvent.ACTION_UP)
myBtn.setImageResource(R.drawable.quit_yes);
return false;
}
});
Or you ca simply create an btn_selector.xml file in your drawable and set that to your ImageBackgroundResource like
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<!-- When selected, you should use bg with grey -->
<item android:drawable="#drawable/pressed_btn"
android:state_selected="true" />
<!-- When not selected, you should use bg with white -->
<item android:drawable="#drawable/nonselected_btn" />
</selector>
And in the java you have to assign your ImageButton background resource as that file
myBtn.setBackgroundResource(R.drawable.btn_selector);
I dynamically generate TextViews which work like buttons. Now i want to highlight them when they get pressed. Something like change Text color or background color.
I have tried to use selector, but it doesn't work.
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:state_focused="true" android:color="#ffffff"/>
<item android:state_pressed="true" android:state_enabled="false" android:color="#ffffff" />
</selector>
Here my loop for creating the TextViews.
int z = 0;
for (MOKGenericDataItem d : data) {
if (d.getButtonText() != null) {
final int pagePosition = z;
TextView btn = new TextView(getActivity());
btn.setId(z);
final int id_ = btn.getId();
btn.setText(d.getButtonText());
btn.setTextSize(TypedValue.COMPLEX_UNIT_SP, 30);
btn.setLayoutParams(new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT, 1f));
btn.setGravity(Gravity.CENTER);
mLineareLayoutViewPagerButtons.addView(btn);
btn1 = ((TextView) view.findViewById(id_));
btn1.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
mViewPager.setCurrentItem(pagePosition,false);
}
});
}
z++;
}
First of all your this line is creating ambiguity as you are taking a variable name as btn1 (which is relating it to button)and you are taking a reference of TextView,
btn1 = ((TextView) view.findViewById(id_));
Anyways,Go step by step,
create an xml like label_bg.xml like the following in the drawable folder:
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:drawable="#drawable/pressed_color"
android:state_pressed="true" />
<item android:drawable="#drawable/normal_color" />
</selector>
In values folder create another xml like the following,named as labelcolors.xml
<?xml version="1.0" encoding="utf-8"?>
<resources>
<drawable name="pressed_color">#7ec0ee</drawable> <!--custom color for pressed state -->
<drawable name="normal_color">#00FFFFFF</drawable> <!--transperent color for normal state -->
</resources>
Now set the background of the label as label_bg.xml
<TextView
android:id="#+id/yourlabel"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="760dp"
android:layout_marginTop="515dp"
android:background="#drawable/label_bg" <!--like this-->
android:text="LabelText"
android:textSize="20dp" />
as you are dynamically adding the views so you need to set the background for your each textView programatically .For that call setBackgroundResource() on the textview object created and set label.xml as background
You need to create a class implements with OnTouchListener and Detect touch Motin. ACTION_DOWN, change text color and ACTION_UP change it's default color according to your requirement.
Code:
public class CustomTouchListener implements View.OnTouchListener {
public boolean onTouch(View view, MotionEvent motionEvent) {
switch (motionEvent.getAction()) {
case MotionEvent.ACTION_DOWN:
((TextView) view).setTextColor(0xFFFFFFFF); // white
break;
case MotionEvent.ACTION_CANCEL:
case MotionEvent.ACTION_UP:
((TextView) view).setTextColor(Color.parseColor("#4a4a4a")); // lightblack
break;
}
return false;
}
}
Now set TouchListener using
textView.setOnTouchListener(new CustomTouchListener());
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.