按钮不将其图像状态更改为“按下”

时间:2012-11-05 09:57:04

标签: android imagebutton selected

我正在尝试做一个简单的选择器。

这是我的选择器xml代码,它叫做“butt.xml”:

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

<item android:drawable="@drawable/btn_activate_on" android:state_pressed="true"/>
<item android:drawable="@drawable/btn_activate_off" android:state_pressed="false"/> <!-- default -->

那就是布局:

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent" >

<ImageButton
    android:id="@+id/imageView1"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_alignParentBottom="true"
    android:layout_centerHorizontal="true"
    android:layout_marginBottom="42dp"
    android:src="@drawable/butt" />

那就是代码:

ImageButton ib;

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    ib = (ImageButton) findViewById(R.id.imageView1);
    ib.setOnClickListener(this);
}

@Override
public void onClick(View v) {
    ib.setSelected(true);

}

当我按住按钮时,我的问题是状态没有改变。当我按下时,它正在将其图像更改为"selected"。但是当我松开手指时,它会回到"not sellected"状态。

为什么会这样?如何让它保持“选定”模式?

3 个答案:

答案 0 :(得分:1)

在选择器butt.xml中使用它

<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">

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

</selector>

此外,您还可以从ib.setSelected(true);中删除此行onClick()。它将被关注。
更新

<ImageButton
    android:id="@+id/imageView1"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_alignParentBottom="true"
    android:layout_centerHorizontal="true"
    android:layout_marginBottom="42dp"
    android:background="@drawable/butt" />

您需要设置背景而不是设置src。

答案 1 :(得分:1)

如果您需要将按钮的状态显示为已选择或未选中,则无需使用选择器。

相反,你必须使用代码setBackground(),并通过管理一个标志,你可以检查你的按钮当前是否被选中。

if(flag)
    btn.setDrawableBackground(R.id.btn_activate_on)
else
    btn.setDrawableBackground(R.id.btn_activate_off)

如果要在状态上显示效果,请按两个具有相反状态的选择器。

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

另一个是

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

答案 2 :(得分:1)

不应该使用按钮进行切换 - 请改用复选框。

按钮的“已选择”表示用户当前将手指放在按钮上,因此当用户抬起手指时,它将不再被选中。

相关问题