Android中ImageButton的运用详解


ImageButton在Android的运用非常灵活,既可以在.java中实现,也可以在.xml中实现,但相比较而言在.xml中实现更有利于代码的改动,现分别讲述以上两种实现方式:

1. 一种是在代码里

自己的图片

m_ImageButton.setImageDrawable(getResources().getDrawable(R.drawable.my_button));

系统自带的图片

m_ImageButton.setImageDrawable(getResources().getDrawable(android.R.drawable.sym_call_incoming));

2. 一种是在XML文件里

自己的图片

android:src="@drawable/ic_media_play"

系统自带的图片

android:src="@android:drawable/sym_call_incoming"

3. 指定按钮的背景图,有state_pressed和state_focused,分别代表按下去和焦点停留(用方向键等控制)时的状态

默认都是false。下面可以实现按下去时的背景图。

在main.xml里添加,

android:background="@drawable/button_add_x"一行。

在res/drawable下添加一个button_add_x。xml的文件

<?xml version="1.0" encoding="utf-8"?>
 <selector xmlns:android="http://schemas.android.com/apk/res/android">
     <item android:state_pressed="true"
           android:drawable="@drawable/ic_media_select" />
 </selector>

相关内容