如何在按下后按下“按下”按钮?

时间:2013-06-24 11:36:01

标签: android button

常规按钮会在按下时更改其外观。即使它被释放,我怎么能在按钮上保持这种“按下”的外观?

3 个答案:

答案 0 :(得分:1)

如果您不想使用ToggleButton,可能的解决方案是在onClickListener中设置布尔值

   private boolean isPressed = false;


    mYourButton.setOnClickListener(new OnClickListener(){

           @Override
            public void onClick(){

                 if(isPressed==false){

                    mYourButton.setBackgroundResource(R.drawable.your_pressed_image);
                    isPressed=true;

                 }else if(isPressed==true){

                      mYourButton.setBackgroundResource(R.drawable.your_default_image);
                      isPressed=false;

                  }
               }
          });

答案 1 :(得分:1)

有一些事情要做,我建议使用drawable和layouts文件。

例如,您有一个视图,其中您有“发送”或“完成按钮”,因此文件夹布局中的视图是这样的:< / p>

<ImageButton
android:id="@+id/btnIdNext"
android:contentDescription="@string/someDescriptionOfImage"
android:layout_width="wrap_content"
android:layout_marginTop="10dp"
android:layout_height="wrap_content"
android:src="@drawable/buttons_src"
android:background="@drawable/buttons"
android:onClick="someaction" />

正如你所看到的,你有两个重要的绘图,src和背景。所以,让我们创建那些文件

在drawable文件夹中,我们创建 buttons_src.xml 文件

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

在drawable文件夹中,我们也创建了 buttons.xml 文件

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

我们得到的是四张图像,两张用于未按下状态,两张用于按下状态。

接下来的预览:

*未按下的按钮 http://i.stack.imgur.com/UZMtt.png

*按下按钮 http://i.stack.imgur.com/1E0u4.png

答案 2 :(得分:0)

你可以使用ToggleButton而不是常规的,在按下后保存状态。

只需使用selector为其分配按下和未按下的纹理,按下它后它将保存按下的纹理。