2012-12-10 57 views
-2

我有一个问题。我不知道如何根据其状态改变按钮的外观。按钮看它的状态

xml中的标准外观不起作用,默认也不起作用。

{ 
    button1 = (Button) findViewById(R.id.button5); 

    button1.setOnTouchListener(new OnTouchListener() { 

     @Override 
     public boolean onTouch(View v, MotionEvent event) { 

       switch (event.getAction()) 
       { 
        case MotionEvent.ACTION_DOWN: 
         mp[0] = loadSample(1); 
         mp[0].start(); 
         break; 
        case MotionEvent.ACTION_UP: 
         mp[0].stop(); 
         //mp.reset(); 
         mp[0].release(); 
         break; 
       } 
     return true; 
     } 
    }); 
} 
+2

什么是MP?你想在哪里改变外观?我会考虑的MediaPlayer – adarsh

+1

。 – AedonEtLIRA

+0

[通过XML点击改变背景的Android按钮]可能的副本(http://stackoverflow.com/questions/4125774/make-an-android-button-change-background-on-click-through-xml) – Matthieu

回答

1

这听起来像你正在寻找ImageButton与图像选择器。这允许您为给定按钮定义pressedfocusednormal状态。

示例从ImageButton API页面直接拉出。一旦实现如下,Android将根据您定义的选择器自动选择适合当前状态的图片。 http://developer.android.com/reference/android/widget/ImageButton.html

由于XML在drawable文件夹:

<?xml version="1.0" encoding="utf-8"?> 
    <selector xmlns:android="http://schemas.android.com/apk/res/android"> 
     <item android:state_pressed="true" android:drawable="@drawable/button_pressed" /> <!-- pressed --> 
     <item android:state_focused="true" android:drawable="@drawable/button_focused" /> <!-- focused --> 
     <item android:drawable="@drawable/button_normal" /> <!-- default --> 
    </selector> 
0

做你做这样的事情在XML?

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

    <item android:drawable="@drawable/myButtonYellow" 
     android:state_pressed="true" /> 
    <item android:drawable="@drawable/myButtonNotYellow" /> 
</selector> 

的机器人:state_pressed =“真”线将设置它,使得其将根据其按下状态而变化。状态的完整列表,可以发现here

myButton的定义为:

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

    <corners android:radius="4dp" /> 

    <solid android:color="@color/yellow" /> 

    <padding 
     android:bottom="7dp" 
     android:left="12dp" 
     android:right="12dp" 
     android:top="7dp" /> 

    <stroke 
     android:width="1dp" 
     android:color="@color/white" /> 

</shape>