Android studio中单击ImageButton按钮变换图片或颜色

学习android studio后,掌握了TextView、Button、EditText、ImageView的使用。今天分享一下有关ImageButton图片按钮的使用,及单击ImageButton(按下、抬起)时变换不同的图片或颜色,希望可以对大家的学习有所帮助。


目录

一、 ImageButton简介

二、Android样式选择器

三、单击ImageButton按钮变换图片

四、单击ImageButton按钮变换颜色


一、 ImageButton简介

  • ImageButton显示一个可以被用户单击的图片按钮,是ImageView的子类。
  • ImageButton可通过属性src设置图像表示按钮的外观。
  • ImageButton的单击事件监听使用setOnTouchListener()方法设置事件监听方法

二、Android样式选择器

作用:处理组件不同状态下展示效果。主要应用是在资源文件的使用。

选择器中的不同状态:

  • android:state_pressed

true指当用户点击或者触摸该控件的状态。默认为false;一般用于按钮颜色/图片的设置

  • android:state_focused

ture指当前控件获得焦点时的状态。默认为false;一般用于EdiText

  • android:state_hovered

true表示光标移动到当前控件上的状态。默认为false;光标是否悬停,通常与state_focused 相同,它是4.0的新特性,一般用于EdiText

  • android:state_selected

true表示被选择的状态,例如在一个下拉列表中用方向键选择其中一个选项。

这个和focus的区别,selected是focus不充分的情况。比如一个listview获得焦点(focus),而用方向键选择了其中的一个item(selected)

  • android:state_checked

true表示当前控件处于被勾选(check的状态)一般用于单选、复选框

三、单击ImageButton按钮变换图片

<ImageButton
        android:id="@+id/imageButton"
        android:layout_width="match_parent"
        android:layout_height="200dp" />
public class MainActivity extends AppCompatActivity {
    private ImageButton imageButton;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        imageButton = findViewById(R.id.imageButton);
        imageButton.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View view, MotionEvent motionEvent) {
                if(motionEvent.getAction() == MotionEvent.ACTION_DOWN){
                    imageButton.setImageResource(R.drawable.book);
                }else if(motionEvent.getAction() == MotionEvent.ACTION_UP){
                    imageButton.setImageResource(R.drawable.lanqiu);
                }
                return false;
            }
        });
    }
}

   

 四、单击ImageButton按钮变换颜色

<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:state_pressed="false" android:drawable="@color/teal_200" />
    <item android:state_pressed="true" android:drawable="@color/purple_200" />
</selector>
<ImageButton
        android:id="@+id/imageButton"
        android:layout_width="match_parent"
        android:layout_height="200dp"
        android:background="@drawable/style"/>

   

 

 

  • 5
    点赞
  • 44
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值