安卓的ImageButton与所选择的状态呢? [英] Android ImageButton with a selected state?

查看:144
本文介绍了安卓的ImageButton与所选择的状态呢?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果我使用的ImageButton的一个选择它的背景,有一个状态,我可以改变,这将使它改变它的外观?现在,我可以得到它来改变图像时pressed,但似乎没有突出或选定的或类似的状态,这让我切换它的外观的意愿。

If I was using an ImageButton with a selector for its background, is there a state I can change which will make it change its appearance? Right now I can get it to change images when pressed, but there seems to be no "highlighted" or "selected" or similar state which lets me toggle its appearance at will.

下面是我的XML;它只会改变时pressed外观。

Here's my XML; it only changes appearance when pressed.

 <selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:state_focused="true" android:state_pressed="false" android:drawable="@drawable/map_toolbar_details_selected" />
<item android:state_focused="true" android:state_pressed="true" android:drawable="@drawable/map_toolbar_details_selected" />
<item android:state_focused="false" android:state_pressed="true" android:drawable="@drawable/map_toolbar_details_selected" />
<item android:drawable="@drawable/map_toolbar_details" />

推荐答案

这对我的作品:

<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
    <!-- NOTE: order is important (the first matching state(s) is what is rendered) -->
    <item 
        android:state_selected="true" 
        android:drawable="@drawable/info_icon_solid_with_shadow" />
    <item 
        android:drawable="@drawable/info_icon_outline_with_shadow" />
 </selector>

然后在Java中:

And then in java:

//assign the image in code (or you can do this in your layout xml with the src attribute)
imageButton.setImageDrawable(getBaseContext().getResources().getDrawable(R.drawable....));

//set the click listener
imageButton.setOnClickListener(new OnClickListener() {

    public void onClick(View button) {
        //Set the button's appearance
        button.setSelected(!button.isSelected());

        if (button.isSelected()) {
            //Handle selected state change
        } else {
            //Handle de-select state change
        }

    }

});

有关平稳过渡,也可以提动画时间:

For smooth transition you can also mention animation time:

<selector xmlns:android="http://schemas.android.com/apk/res/android" android:exitFadeDuration="@android:integer/config_mediumAnimTime">

这篇关于安卓的ImageButton与所选择的状态呢?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆