如何修改Android中的默认按钮状态而不影响按下和选择的状态?

2 android default button selector

我试图仅在默认状态下删除ImageButton的背景.我希望按下和选择的状态像往常一样运行,以便它们在不同的设备上看起来正确,这些设备对于按下和选择的状态使用不同的颜色.

有没有办法设置ImageButton的背景默认状态的drawable而不影响按下和选择状态?

我试图用选择器做这个,但它似乎不允许你在某些状态下使用默认的drawable - 你必须自己设置所有的状态.由于没有API来检索设备的默认按下/选定的drawable,我不知道将按下/选择的状态设置为什么.

我还尝试获取系统在您不使用选择器时创建的按钮的StateListDrawable对象,然后修改它更改默认状态.那也行不通.

我似乎在Android上,如果你想改变一个按钮状态的drawable,那么你必须设置所有状态,因此不能保留其他状态的默认drawable.它是否正确?

谢谢!-Tom B.

dan*_*h32 5

汤姆,

确实如果你覆盖默认状态,你还必须覆盖按下和聚焦的状态.原因是默认的android drawable是一个选择器,所以用静态drawable覆盖它意味着你丢失了压缩和聚焦状态的状态信息,因为你只有一个指定的drawable.但是,实现自定义选择器非常容易.做这样的事情:

<selector
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/custombutton">

    <item
        android:state_focused="true"
        android:drawable="@drawable/focused_button" />
    <item
        android:state_pressed="true"
        android:drawable="@drawable/pressed_button" />
    <item
        android:state_pressed="false"
        android:state_focused="false"
        android:drawable="@drawable/normal_button" />
</selector>
Run Code Online (Sandbox Code Playgroud)

将它放在drawables目录中,并像ImageButton背景的普通drawable一样加载它.对我来说最困难的部分是设计实际图像.

编辑:

刚刚开始深入研究EditText的源代码,这就是他们设置背景drawable的方式:

public EditText(/*Context context, AttributeSet attrs, int defStyle*/) {
    super(/*context, attrs, defStyle*/);

            StateListDrawable mStateContainer = new StateListDrawable();

            ShapeDrawable pressedDrawable = new ShapeDrawable(new RoundRectShape(10,10));
            pressedDrawable.getPaint().setStyle(Paint.FILL);
            pressedDrawable.getPaint().setColor(0xEDEFF1);


            ShapeDrawable focusedDrawable = new ShapeDrawable(new RoundRectShape(10,10));
            focusedDrawable.getPaint().setStyle(Paint.FILL);
            focusedDrawable.getPaint().setColor(0x5A8AC1);

            ShapeDrawable defaultDrawable = new ShapeDrawable(new RoundRectShape(10,10));
            defaultDrawable.getPaint().setStyle(Paint.FILL);
            defaultDrawable.getPaint().setColor(Color.GRAY);



            mStateContainer.addState(View.PRESSED_STATE_SET, pressedDrawable);
            mStateContainer.addState(View.FOCUSED_STATE_SET, focusedDrawable);
            mStateContainer.addState(StateSet.WILD_CARD, defaultDrawable);

            this.setBackgroundDrawable(mStateContainer);
}
Run Code Online (Sandbox Code Playgroud)

我相信你可以根据你的目的调整这个想法.这是我发现它的页面:

http://www.google.com/codesearch/p?hl=en#ML2Ie1A679g/src/android/widget/EditText.java