[英]How can I give an imageview click effect like a button on Android?
我在我的 Android 应用程序中有 imageview,我使用它就像一个带有 onClick 事件的按钮,但你可能猜到它在单击时不会给 imageview 一个可点击的效果。 我怎样才能做到这一点?
您可以使用以下方法对单个图像执行此操作:
//get the image view
ImageView imageView = (ImageView)findViewById(R.id.ImageView);
//set the ontouch listener
imageView.setOnTouchListener(new OnTouchListener() {
@Override
public boolean onTouch(View v, MotionEvent event) {
switch (event.getAction()) {
case MotionEvent.ACTION_DOWN: {
ImageView view = (ImageView) v;
//overlay is black with transparency of 0x77 (119)
view.getDrawable().setColorFilter(0x77000000,PorterDuff.Mode.SRC_ATOP);
view.invalidate();
break;
}
case MotionEvent.ACTION_UP:
case MotionEvent.ACTION_CANCEL: {
ImageView view = (ImageView) v;
//clear the overlay
view.getDrawable().clearColorFilter();
view.invalidate();
break;
}
}
return false;
}
});
我可能会将它变成 ImageView 的子类(或 ImageButton,因为它也是 ImageView 的子类)以便于重用,但这应该允许您将“选定”外观应用于图像视图。
您可以为点击/未点击状态设计不同的图像,并在 onTouchListener 中进行如下设置
final ImageView v = (ImageView) findViewById(R.id.button0);
v.setOnTouchListener(new OnTouchListener() {
@Override
public boolean onTouch(View arg0, MotionEvent arg1) {
switch (arg1.getAction()) {
case MotionEvent.ACTION_DOWN: {
v.setImageBitmap(res.getDrawable(R.drawable.img_down));
break;
}
case MotionEvent.ACTION_CANCEL:{
v.setImageBitmap(res.getDrawable(R.drawable.img_up));
break;
}
}
return true;
}
});
更好的选择是你定义一个选择器如下
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:state_selected="true"
android:drawable="@drawable/img_down" />
<item android:state_selected="false"
android:drawable="@drawable/img_up" />
</selector>
并选择事件中的图像:
v.setOnTouchListener(new OnTouchListener() {
@Override
public boolean onTouch(View arg0, MotionEvent arg1) {
v.setSelected(arg1.getAction()==MotionEvent.ACTION_DOWN);
return true;
}
});
编辑:虽然下面的原始答案有效且易于设置,但如果您想要/需要更有效的实现,请参阅 Google 的 Android 开发人员倡导者的这篇文章。 另请注意,默认情况下,Android M 中的android:foreground
属性将适用于所有 Views ,包括 ImageView 。
为 ImageView 使用选择器的问题是你只能将它设置为视图的背景——只要你的图像不透明,你就不会看到它背后的选择器效果。
诀窍是将您的 ImageView 包装在具有android:foreground
属性的 FrameLayout 中,这允许我们为其内容定义叠加层。 如果我们将android:foreground
设置为选择器(例如?android:attr/selectableItemBackground
for API level 11+)并将OnClickListener
附加到 FrameLayout 而不是 ImageView,图像将与我们的选择器的 drawable 重叠 - 我们想要的点击效果!
看:
<FrameLayout
android:id="@+id/imageButton"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:foreground="?android:attr/selectableItemBackground" >
<ImageView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:src="@drawable/yourImageFile" />
</FrameLayout>
(注意这应该放在你的父布局中。)
final View imageButton = findViewById(R.id.imageButton);
imageButton.setOnClickListener(new OnClickListener(){
@Override
public void onClick(View view) {
// do whatever we wish!
}
});
使用 ColorFilter 方法可以只处理一个图像文件。 但是,ColorFilter 期望使用 ImageViews 而不是 Buttons,因此您必须将按钮转换为 ImageViews。 无论如何,如果您使用图像作为按钮,这不是问题,但是如果您有文本,那就更烦人了……无论如何,假设您找到解决文本问题的方法,以下是要使用的代码:
ImageView button = (ImageView) findViewById(R.id.button);
button.setColorFilter(0xFFFF0000, PorterDuff.Mode.MULTIPLY);
这将红色覆盖应用于按钮(颜色代码是完全不透明红色的十六进制代码 - 前两位数字是透明的,然后是 RR GG BB。)。
在 XML 文件中使用style="?android:borderlessButtonStyle" 。 它将显示Android默认点击效果。
<ImageView
android:id="@+id/imageView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="@drawable/ic_launcher"
style="?android:borderlessButtonStyle"
/>
只需使用ImageButton 即可。
这是我解决这个问题的简单方法:
ImageView iv = (ImageView) findViewById(R.id.imageView);
iv.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
//Agrega porcentajes de cada fraccion de grafica pastel
Animation animFadein = AnimationUtils.loadAnimation(getApplicationContext(),R.anim.fade_in);
iv.startAnimation(animFadein);
});
在文件res/anim/fade_in.xml
:
<?xml version="1.0" encoding="utf-8"?>
<set xmlns:android="http://schemas.android.com/apk/res/android"
android:fillAfter="true" >
<alpha
android:duration="100"
android:fromAlpha="0.0"
android:interpolator="@android:anim/accelerate_interpolator"
android:toAlpha="1.0" />
</set>
将可选背景设置为 ImageView 并添加一些填充。 然后附加OnClickListener
。
<ImageView
android:id="@+id/your_image_view"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="@drawable/your_image"
android:padding="10dp"
android:background="?android:attr/selectableItemBackground"/>
如果您想要点击时出现涟漪,可以通过以下代码给出:
<ImageView
...
android:background="?attr/selectableItemBackgroundBorderless"
android:clickable="true"
...
</ImageView>
同样可以为TextView实现点击效果
<TextView
...
android:background="?attr/selectableItemBackgroundBorderless"
android:clickable="true"
...
</TextView>
用于定义选择器可绘制选项
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:state_selected="true"
android:drawable="@drawable/img_down" />
<item android:state_selected="false"
android:drawable="@drawable/img_up" />
</selector>
我必须使用 android:state_pressed 而不是 android:state_selected
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:state_pressed ="true"
android:drawable="@drawable/img_down" />
<item android:state_pressed ="false"
android:drawable="@drawable/img_up" />
</selector>
这对我有用:
img.setOnTouchListener(new OnTouchListener(){
@Override
public boolean onTouch(View v, MotionEvent event) {
switch (event.getAction())
{
case MotionEvent.ACTION_DOWN:
{
((ImageView)v).setImageAlpha(200);
break;
}
case MotionEvent.ACTION_MOVE:
{
// if inside bounds
if(event.getX() > 0 && event.getX() < v.getWidth() && event.getY() > 0 && event.getY() < v.getHeight())
{
((ImageView)v).setImageAlpha(200);
}
else
{
((ImageView)v).setImageAlpha(255);
}
break;
}
case MotionEvent.ACTION_UP:
{
((ImageView)v).setImageAlpha(255);
}
}
return true;
}
});
@Edit:正如 Gunhan 所说,setImageAlpha 方法会存在向后兼容性问题。 我用了这个方法:
public static void setImageAlpha(ImageView img, int alpha)
{
if(Build.VERSION.SDK_INT > 15)
{
img.setImageAlpha(alpha);
}
else
{
img.setAlpha(alpha);
}
}
您可以尝试使用android:background="@android:drawable/list_selector_background"
获得与默认“闹钟”(现在是桌面时钟)中的“添加闹钟”相同的效果。
我做一些类似的事情 看适合不适合你
查看印刷效果助手:
用法:做一些像iOS一样的简单按压效果
简单用法:
ImageView img = (ImageView) findViewById(R.id.img);
结合上面的所有答案,我希望 ImageView 被按下并改变状态,但如果用户移动然后“取消”而不执行 onClickListener。
我最终在类中创建了一个 Point 对象,并根据用户按下 ImageView 的时间设置其坐标。 在 MotionEvent.ACTION_UP 上,我记录了一个新点并比较了这些点。
我只能解释得很好,但这就是我所做的。
// set the ontouch listener
weatherView.setOnTouchListener(new OnTouchListener() {
@Override
public boolean onTouch(View v, MotionEvent event) {
// Determine what action with a switch statement
switch (event.getAction()) {
// User presses down on the ImageView, record the original point
// and set the color filter
case MotionEvent.ACTION_DOWN: {
ImageView view = (ImageView) v;
// overlay is black with transparency of 0x77 (119)
view.getDrawable().setColorFilter(0x77000000,
PorterDuff.Mode.SRC_ATOP);
view.invalidate();
p = new Point((int) event.getX(), (int) event.getY());
break;
}
// Once the user releases, record new point then compare the
// difference, if within a certain range perform onCLick
// and or otherwise clear the color filter
case MotionEvent.ACTION_UP: {
ImageView view = (ImageView) v;
Point f = new Point((int) event.getX(), (int) event.getY());
if ((Math.abs(f.x - p.x) < 15)
&& ((Math.abs(f.x - p.x) < 15))) {
view.performClick();
}
// clear the overlay
view.getDrawable().clearColorFilter();
view.invalidate();
break;
}
}
return true;
}
});
我在 imageView 上设置了一个 onClickListener,但这可以是一种方法。
您可以覆盖 ImageView 中的setPressed
并在那里进行颜色过滤,而不是创建 onTouchEvent 侦听器:
@Override
public void setPressed(boolean pressed) {
super.setPressed(pressed);
if(getDrawable() == null)
return;
if(pressed) {
getDrawable().setColorFilter(0x44000000, PorterDuff.Mode.SRC_ATOP);
invalidate();
}
else {
getDrawable().clearColorFilter();
invalidate();
}
}
根据Zorn 先生的回答,我在抽象 Utility 类中使用了静态方法:
public abstract class Utility {
...
public static View.OnTouchListener imgPress(){
return imgPress(0x77eeddff); //DEFAULT color
}
public static View.OnTouchListener imgPress(final int color){
return new View.OnTouchListener() {
@Override
public boolean onTouch(View v, MotionEvent event) {
switch(event.getAction()) {
case MotionEvent.ACTION_DOWN: {
ImageView view = (ImageView) v;
view.getDrawable().setColorFilter(color, PorterDuff.Mode.SRC_ATOP);
view.invalidate();
break;
}
case MotionEvent.ACTION_UP:
v.performClick();
case MotionEvent.ACTION_CANCEL: {
ImageView view = (ImageView) v;
//Clear the overlay
view.getDrawable().clearColorFilter();
view.invalidate();
break;
}
}
return true;
}
};
}
...
}
然后我将它与 onTouchListener 一起使用:
ImageView img=(ImageView) view.findViewById(R.id.image);
img.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) { /* Your click action */ }
});
img_zc.setOnTouchListener(Utility.imgPress()); //Or Utility.imgPress(int_color_with_alpha)
如果你有很多图片,并且你想要一个简单的 onTouch 效果,没有任何 XML drawable 并且只有一张图片,这很简单。
我在这里创建示例,只需从布局中将 ImageView 更改为ClickableImageView 。 希望有帮助。
使用android.widget.Button
,并将其background
属性设置为android.graphics.drawable.StateListDrawable
。 这一切都可以在 XML 中或以编程方式完成。 请参阅Form Stuff 教程的自定义按钮部分。
我认为 ImageButton 是一个更好的解决方案
<ImageButton
android:layout_width="96dp"
android:layout_height="56dp"
android:src="@mipmap/ic_launcher"
android:adjustViewBounds="true"
android:background="@android:color/transparent"
android:foreground="@drawable/selector" />
如果你使用背景图片,我有一个更美丽的解决方案:)
public static void blackButton(View button){
button.setOnTouchListener(new OnTouchListener() {
public boolean onTouch(View v, MotionEvent event) {
switch (event.getAction()) {
case MotionEvent.ACTION_DOWN: {
v.getBackground().setColorFilter(0xf0f47521,PorterDuff.Mode.SRC_ATOP);
v.invalidate();
break;
}
case MotionEvent.ACTION_UP: {
v.getBackground().clearColorFilter();
v.invalidate();
break;
}
}
return false;
}
});
}
这是我的解决方案,它使用“ nineOldAndroids ”库,也支持旧的 API:
rootView.setOnTouchListener(new OnTouchListener() {
@Override
public boolean onTouch(final View v, final MotionEvent event) {
switch (event.getAction()) {
case MotionEvent.ACTION_UP:
case MotionEvent.ACTION_CANCEL:
v.setBackgroundResource(R.drawable.listview_normal);
ViewHelper.setAlpha(imageView, 1);
break;
case MotionEvent.ACTION_DOWN:
v.setBackgroundResource(0);
v.setBackgroundColor(getResources().getColor(R.color.listview_pressed));
ViewHelper.setAlpha(imageView, 0.75f);
break;
}
return false;
}
});
它假定 rootView 是单元格本身(布局),并且它有一个图像视图,您希望它受到您希望应用于整个单元格的颜色的影响。
编辑:如果您愿意,您还可以扩展 ImageView 来处理前景,并将其设置为“?android:attr/selectableItemBackground”。 这里有一个库,还有一个关于如何为您希望的任何视图执行此操作的教程, 这里。
或:
您可以使用此表单和图像按钮。
创建文件res/drawable/btn_video.xml
:
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:drawable="@drawable/image"
android:state_pressed="true" />
<item android:drawable="@drawable/ico2"
android:state_focused="true" />
<item android:drawable="@drawable/ico2" />
</selector>
和res/layout/activity_main.xml
:
<ImageButton
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="@+id/imageButton"
android:layout_gravity="center_horizontal"
android:onClick="eventImageBtn"
android:background="@drawable/btn_video"
android:adjustViewBounds="true"
android:scaleType="fitXY"
/>
单击一下即可更改图像,并且可以使用线性布局进行调整:
<?xml version="1.0" encoding="utf-8"?>
<ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:fillViewport="true">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:background="@color/menu_item_background">
<LinearLayout android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical"
android:paddingLeft="@dimen/main_screen_side_padding" android:paddingRight="@dimen/main_screen_side_padding" android:paddingTop="@dimen/main_screen_side_padding" android:paddingBottom="@dimen/main_screen_side_padding"
android:background="#ffb3ff13" android:weightSum="10.00">
<LinearLayout android:layout_weight="2.50" android:background="#ff56cfcd" android:orientation="vertical" android:layout_width="fill_parent" android:layout_height="0dp" >
<ImageButton
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="@+id/imageButton"
android:layout_gravity="center_horizontal"
android:onClick="eventImageBtn"
android:background="@drawable/btn_video"
android:adjustViewBounds="true"
android:scaleType="fitXY"
/>
</LinearLayout>
<LinearLayout android:layout_weight="0.50" android:layout_height="0dp" android:background="#ffffffff" android:orientation="vertical" android:layout_width="fill_parent" >
</LinearLayout>
<LinearLayout android:layout_weight="4.50" android:orientation="vertical" android:layout_width="fill_parent" android:layout_height="0dp" android:background="#ff8aa5ff">
</LinearLayout>
<LinearLayout android:layout_weight="0.50" android:layout_height="0dp" android:background="#ffffffff" android:orientation="vertical" android:layout_width="fill_parent" >
</LinearLayout>
<LinearLayout android:layout_weight="2.00" android:orientation="vertical" android:layout_width="fill_parent" android:layout_height="0dp" android:background="#ffff7d1a" >
</LinearLayout>
</LinearLayout>
</LinearLayout>
</ScrollView>
感谢您对此线程的帮助。 但是,您错过了一件事……您还需要处理 ACTION_CANCEL。 如果不这样做,则在视图层次结构中的父视图拦截触摸事件的情况下,您可能无法正确恢复 ImageView 的 alpha 值(认为 ScrollView 包装了您的 ImageView)。
这是一个基于上述类的完整类,但也处理 ACTION_CANCEL。 它使用 ImageViewCompat 帮助器类来抽象前后 JellyBean API 中的差异。
public class ChangeAlphaOnPressedTouchListener implements OnTouchListener {
private final float pressedAlpha;
public ChangeAlphaOnPressedTouchListener(float pressedAlpha) {
this.pressedAlpha = pressedAlpha;
}
@Override
public boolean onTouch(View v, MotionEvent event) {
ImageView iv = (ImageView) v;
switch (event.getAction()) {
case MotionEvent.ACTION_DOWN:
ImageViewCompat.setAlpha(iv, pressedAlpha);
break;
case MotionEvent.ACTION_MOVE:
if (isInsideViewBounds(v, event)) {
ImageViewCompat.setAlpha(iv, pressedAlpha);
} else {
ImageViewCompat.setAlpha(iv, 1f);
}
break;
case MotionEvent.ACTION_UP:
ImageViewCompat.setAlpha(iv, 1f);
break;
case MotionEvent.ACTION_CANCEL:
ImageViewCompat.setAlpha(iv, 1f);
}
return false;
}
private static boolean isInsideViewBounds(View v, MotionEvent event) {
return event.getX() > 0 && event.getX() < v.getWidth() && event.getY() > 0
&& event.getY() < v.getHeight();
}
}
这是我的代码。 这个想法是当用户触摸它时 ImageView 获得滤色器,当用户停止触摸它时滤色器被移除。
Martin Booka Weser、András、Ah Lam、altosh,当 ImageView 也有 onClickEvent 时,解决方案不起作用。 worawee.s 和 kcoppock (with ImageButton) 解决方案需要背景,当 ImageView 不透明时没有意义。
这是AZ_关于滤色器的想法的延伸。
class PressedEffectStateListDrawable extends StateListDrawable {
private int selectionColor;
public PressedEffectStateListDrawable(Drawable drawable, int selectionColor) {
super();
this.selectionColor = selectionColor;
addState(new int[] { android.R.attr.state_pressed }, drawable);
addState(new int[] {}, drawable);
}
@Override
protected boolean onStateChange(int[] states) {
boolean isStatePressedInArray = false;
for (int state : states) {
if (state == android.R.attr.state_pressed) {
isStatePressedInArray = true;
}
}
if (isStatePressedInArray) {
super.setColorFilter(selectionColor, PorterDuff.Mode.MULTIPLY);
} else {
super.clearColorFilter();
}
return super.onStateChange(states);
}
@Override
public boolean isStateful() {
return true;
}
}
用法:
Drawable drawable = new FastBitmapDrawable(bm);
imageView.setImageDrawable(new PressedEffectStateListDrawable(drawable, 0xFF33b5e5));
我认为最简单的方法是创建一个新的 XML 文件。 在这种情况下,我们在drawable文件夹中将其称为“example.xml”,并放入以下代码:
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:drawable="@color/blue"
android:state_pressed="true" />
</selector>
但在此之前,您必须在 values 文件夹中的 colors.xml 文件中设置颜色,如下所示:
<resources>
<color name="blue">#0000FF</color>
</resources>
这样,您只需将 Button / ImageButton 设置为使用新布局,如下所示:
<ImageView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:background="@drawable/example"
/>
然后当您单击该图像时,它将更改为设置的颜色
<item android:drawable="@color/blue"
android:state_pressed="true" />
提供您想要的反馈...
我试过:
<ImageButton
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:contentDescription="@string/get_started"
android:src="@drawable/home_started"
style="?android:borderlessButtonStyle"
android:adjustViewBounds="true"
android:clickable="true"
android:elevation="5dp"
android:longClickable="true" />
这有效。 请注意这一行: style="?android:borderlessButtonStyle"
这是我见过的最好的解决方案。 它更通用。
<?xml version="1.0" encoding="utf-8"?>
<set xmlns:android="http://schemas.android.com/apk/res/android"
android:fillAfter="true" >
<alpha
android:duration="100"
android:fromAlpha="0.0"
android:interpolator="@android:anim/accelerate_interpolator"
android:toAlpha="1.0" />
</set>
我在Android应用程序中使用了imageview,就像按钮一样使用了onClick事件,但是您可能会猜想它在单击时并没有给imageview提供可点击的效果。 我该如何实现?
我在Android应用程序中使用了imageview,就像按钮一样使用了onClick事件,但是您可能会猜想它在单击时并没有给imageview提供可点击的效果。 我该如何实现?
只需添加XML属性,android:clickable =“true”...
您可以为ImageView
制作一个简单的涟漪效果。 这非常适合图标。
在res/drawable
创建circular_shape.xml
:
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item>
<shape android:shape="oval">
<solid android:color="@android:color/white"/>
</shape>
</item>
在res/drawable
创建一个可绘制的 res 文件ripple_effect_iv.xml
:
<ripple xmlns:android="http://schemas.android.com/apk/res/android"
android:color="?attr/colorControlHighlight">
<item
android:id="@android:id/mask"
android:drawable="@drawable/circular_shape" />
</ripple>
将其设置为ImageView
background
,您也可以考虑padding
以显示自然波纹:
<ImageView
android:background="@drawable/ripple_effect_iv"
android:padding="10dp"/>
是的,您的ImageView
变小了,但您可以简单地增加android:layout_width
和android:layout_height
。
至于现在,我们应该发展Material Design实践。 在这种情况下,您可以在 ImageView 上添加涟漪效果。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.