zoukankan      html  css  js  c++  java
  • android 中ImageButton按下改变背景图片的效果

    最近在做一个app的登陆界面,才发现原来认为很简单的UI效果,其实背后却蕴含的知识很多,积累一个算一个吧。
    实现方法有两种:一种是添加代码,一种是配置xml文件。
    方法一:代码添加

    ImageButton btn = (ImageButton)findViewById(R.id.imageButton1); 

    btn.setOnTouchListener(new View.OnTouchListener(){ 

    public boolean onTouch(View v, MotionEvent event) { 

    if(event.getAction() == MotionEvent.ACTION_DOWN){ 

    //重新设置按下时的背景图片

    ((ImageButton)v).setImageDrawable(getResources().getDrawable(R.drawable.android_btn_pressed)); 

    }else if(event.getAction() == MotionEvent.ACTION_UP){ 

    //再修改为抬起时的正常图片

    ((ImageButton)v).setImageDrawable(getResources().getDrawable(R.drawable.android_btn)); 

    return false; 

    }); 

     方法2:配置xml文件
    步骤1:在Layout下增加一个image_btn_press.xml文件

    <?xml version="1.0" encoding="utf-8"?>

    <selectorxmlns:android="http://schemas.android.com/apk/res/android">

    <item android:state_pressed="false"android:drawable="@drawable/android_btn" />

    <item android:state_focused="true"android:drawable="@drawable/android_btn" />

    <item android:state_pressed="true"android:drawable="@drawable/android_btn_pressed" />

    </selector>

    步骤2:在main.xml中设置图片按钮的属性,装上面的xml文件增加到图片按钮中

    <ImageButton

    android:id="@+id/imageButton2"

    android:layout_width="wrap_content"

    android:layout_height="wrap_content"

    android:background="@layout/image_btn_press" />

     需要特别注意的是在ImageButton中,如果使用XML配置文件来设置图片的效果的话,就不要再指定它的android:src=""属性值了,否则图片的按下效果就出不来了。
  • 相关阅读:
    88. 合并两个有序数组
    680. 验证回文字符串 Ⅱ
    345. 反转字符串中的元音字母
    633. 平方数之和
    分支程序设计
    scanf函数(初学者)
    输入与输出(初学者)
    C语句详细(初学者)
    算术运算符和算术表达式(初学者)
    变量赋值(初学者)
  • 原文地址:https://www.cnblogs.com/qingchen1984/p/4918075.html
Copyright © 2011-2022 走看看