100字范文,内容丰富有趣,生活中的好帮手!
100字范文 > Android studio中单击ImageButton按钮变换图片或颜色

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

时间:2020-04-14 11:05:42

相关推荐

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按钮变换图片

<ImageButtonandroid:id="@+id/imageButton"android:layout_width="match_parent"android:layout_height="200dp" />

public class MainActivity extends AppCompatActivity {private ImageButton imageButton;@Overrideprotected void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);setContentView(R.layout.activity_main);imageButton = findViewById(R.id.imageButton);imageButton.setOnTouchListener(new View.OnTouchListener() {@Overridepublic 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="/apk/res/android"><item android:state_pressed="false" android:drawable="@color/teal_200" /><item android:state_pressed="true" android:drawable="@color/purple_200" /></selector>

<ImageButtonandroid:id="@+id/imageButton"android:layout_width="match_parent"android:layout_height="200dp"android:background="@drawable/style"/>

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。