您的位置:首页 > 移动开发 > Android开发

Android点击图片切换(用XML)

2015-08-03 09:45 453 查看
在css中<a 标签可以通过伪类的方式实现鼠标略过,鼠标点击前后的不同样式,在Android,可以通过设置View的“android:background”属性或在代码中通过setBackgroundDrawable()方法设置点击前后View的不同图片。
下面简单介绍下xml和代码两种方式:

1、xml 方式实现

1.1在res/drawable下新建一个xml 如 mybg.xml,具体内容如下:

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

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

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

<item android:state_focused="false" android:state_pressed="true" android:drawable="@drawable/menu_home" />

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

<item android:state_focused="false" android:drawable="@drawable/menu_home_g" />

</selector>

1.2把view对应的android:background指向mybg,如

<TextView android:id="@+id/tvTest" android:background="@drawable/mybg" ...

2、代码方式实现

StateListDrawable drawable = new StateListDrawable();

try {

drawable.addState(new int []{android.R.attr.state_focused, android.R.attr.state_enabled}, context.getResources().getDrawable(R.drawable.menu_focused));

drawable.addState(new int []{android.R.attr.state_pressed, android.R.attr.state_enabled}, context.getResources().getDrawable(R.drawable.menu_pressed));

drawable.addState(new int []{android.R.attr.state_checked, android.R.attr.state_enabled}, context.getResources().getDrawable(R.drawable.menu_clicked));

drawable.addState(new int []{android.R.attr.state_selected, android.R.attr.state_enabled}, context.getResources().getDrawable(R.drawable.menu_selected));

drawable.addState(new int []{}, context.getResources().getDrawable(R.drawable.menu_default));

} catch (Exception e) {

e.printStackTrace();

}

TextView view = new TextView(context);

view.setBackgroundDrawable(drawable);

部分view没有selected效果,只有radioButton等才有该效果。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: