如何在 Android 中设置按钮点击效果?

在 Android 中,当我为一个按钮设置背景图像时,我不能看到它被点击时的任何效果。

I need to set some effect on the button, so the user can recognise that the button is clicked.

按钮应该是黑暗的几秒钟,当它被点击。如何做到这一点?

293557 次浏览

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>

为了在新闻中保持背景图像的黑暗外观,创建第二个 xml 文件并使用以下代码将其命名为 gradient.xml:

<?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>

在按钮的 xml 中,将背景设置为按钮 xml。

android:background="@drawable/button"

更改了上面的代码,以显示按钮中的图像(YOURIMAGE) ,而不是块颜色。

如果有很多图像按钮,并且不希望为每个按钮编写 xml-s,那么这样做就更简单了。

科特林版本:

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 版本:

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;
}
});
}

只是想添加另一个简单的方法来做到这一点: 如果你的 ImageButton 仍然是它的背景,你不设置为空,它将工作像一个正常的按钮,并会显示点击动画,而点击完全一样的其他按钮。如何在背景还在的时候隐藏它:

<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" />

填充不会让背景显示出来,并使按钮像其他按钮一样工作。

创建您的 AlphaAnimation对象,决定多少将是褪色效果的按钮,然后让它开始在您的按钮的 onClickListener

例如:

private AlphaAnimation buttonClick = new AlphaAnimation(1F, 0.8F);


// some code


public void onClick(View v) {
v.startAnimation(buttonClick);
}

当然,这只是一种方式,不是最喜欢的方式,它只是更容易

或者只使用一个背景图片,你可以通过使用 setOnTouchListener实现点击效果

两条路

((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;
}
});

enter image description here

如果您不想使用 setOnTouchLister,另一种实现方法是

    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);
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

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

这是我从@Vinayak 的回答中得到的最好的解决方案。所有其他的解决方案都有不同的缺点。

首先创建一个这样的函数。

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);
}

说明:

GetConstantState () . newDrawable ()用于克隆现有的 Drawable,否则将使用相同的 Drawable: Android: 为了使 StateListDrawable 具有过滤器,克隆一个可绘制的文件

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

用法:

您可以传递任何类型的视图(按钮,图像按钮,视图等)作为参数的功能,他们将获得应用于他们的点击效果。

addClickEffect(myButton);
addClickEffect(myImageButton);

对安德拉斯的回答稍作补充:

你可以使用 postDelayed使颜色过滤器持续一小段时间,使它更加明显:

        @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;
}

您可以更改延迟100L 的值以满足您的需要。

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.

您可以简单地为您的 View 使用前景实现点击效果:

android:foreground="?android:attr/selectableItemBackground"


使用与黑暗的主题也添加 theme到您的 layout(点击效果是明确的) :

android:theme="@android:style/ThemeOverlay.Material.Dark"

使用 RippleDrawable 对材质设计状态进行压制/点击效果。为了实现这一点,创建涟漪项目作为一个。并将其用于 android: back 中的任何视图。

  • 对于按下/点击图标的效果,使用圆形波纹效果,例如:

    < 涟漪 xmlns: android = “ http://schemas.android.com/apk/res/android”> 机器人: color = “@android: color/dark _ gray” 图片/>

  • 视图效果点击矩形边界,我们可以在现有的图形上添加涟漪,如下图:

    Xml version = “1.0”coding = “ utf-8”? > <ripple xmlns:android="http://schemas.android.com/apk/res/android" Android: color = “ # 000000”> < item android: draable = “@draable/your _ back _ draable”/> [连锁反应]

所有的观点

android:background="?android:attr/selectableItemBackground"

但是对于有高度使用的风景

android:foreground="?android:attr/selectableItemBackground"

对于工具栏中的循环单击效果

android:background="?android:attr/actionBarItemBackground"

你还需要设置

 android:clickable="true"
android:focusable="true"

为动画创建 bunce.xml 文件

地点:

Res-> anim-> bunce.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>

点击中添加此行以初始化

  final Animation myAnim = AnimationUtils.loadAnimation(this,R.anim.bounce);
button.startAnimation(myAnim);

点击一下按钮就能得到收缩效果。

我有同样的问题,我需要有一个透明的背景,但仍然得到动画。设置这个为我解决了问题:

android:background="?android:selectableItemBackground"

如果你想要有圆形效果,也可以这样做:

android:background="?android:selectableItemBackgroundBorderless"

设置视图单击效果的简单方法。

方法

public AlphaAnimation clickAnimation() {
return new AlphaAnimation(1F, 0.4F); // Change "0.4F" as per your recruitment.
}

设置在视图中

yourView.startAnimation(clickAnimation());