2011-10-04 114 views
0

我正在Android上制作一个图形密集型应用程序。我必须制作一个按钮来启用和禁用应用程序的声音,这在应用程序中很常见。我实际上找不到正确的方法来做到这一点。我已经设法通过xml文件切换图像,但仍然失去了如何为这些功能添加功能。将功能添加到ToggleButton,

代码如下.. 主要布局

<Button android:id="@+id/InfoButton" android:background="@drawable/infoiconlow" android:layout_gravity="top|left" android:layout_height="40dp" android:layout_width="30dp" android:layout_marginTop="2dp" android:layout_marginLeft="125dp"></Button> 
    <Button android:layout_gravity="top|right" android:layout_width="wrap_content" android:id="@+id/ForwardButton" android:layout_height="wrap_content" android:background="@drawable/forwardbuttonlow" android:layout_marginRight="10dp" android:layout_marginTop="-3dp"></Button> 
    <ImageView android:src="@drawable/selectthescenetitle" android:id="@+id/imageView3" android:layout_gravity="top|center" android:layout_marginLeft="15dp" android:layout_marginTop="-3dp" android:layout_width="219dp" android:layout_height="wrap_content"></ImageView> 
    <ToggleButton android:id="@+id/MusicButton" android:background="@drawable/shufflebutton" android:textOn="" android:textOff="" android:layout_gravity="top|left" android:layout_width="30dp" android:layout_height="40dp" android:layout_marginTop="2dp" android:layout_marginLeft="84dp" android:clickable="true"> 
    </ToggleButton> 

sufflebutton.xml

<?xml version="1.0" encoding="utf-8"?> 
<layer-list 
    xmlns:android="http://schemas.android.com/apk/res/android"> 
<item android:drawable="@drawable/shufflebuttonimage" /> 
</layer-list> 

shufflebuttonimage.xml

<?xml version="1.0" encoding="utf-8"?> 
<selector xmlns:android="http://schemas.android.com/apk/res/android" > 
    <item android:drawable="@drawable/musiconiconlow" android:state_checked="false" /> 
    <item android:drawable="@drawable/musicofficonlow"/> 
</selector> 

图像切换,但如果我来回走,状态恢复为默认状态,并且我无法为切换添加功能,例如。启用和禁用声音。任何人都可以请帮我解决这个问题,它的驾驶我疯了..

谢谢:)

+0

你的意思是你不知道如何回应它的状态改变事件?使用[setOnCheckChangedListener](http://developer.android.com/reference/android/widget/CompoundButton.html#setOnCheckedChangeListener(android.widget.CompoundButton.OnCheckedChangeListener)) –

+0

我的意思是我希望我的切换按钮的状态根据声音,即启用或禁用PLUS,当我点击按钮,它设置切换按钮的状态,以及... 你能指导我一点点吧.. –

回答

0

我通常实现像这样的代码:

private void initialise(final Context context) 
{  
    final ToggleButton music = (ToggleButton)findViewById(R.id.MusicButton); 


    music.setOnClickListener(new OnClickListener() 
    { 
     @Override 
     public void onClick(View v) 
     {    
      music.setChecked(true);    
      // Do other stuff like play the music. 
     } 
    }); 
} 

因为你将可能有完整的功能在做任何事之前检查按钮的检查状态。

+0

我要去我的大学几个讲座,我会爱回到你身边,并尝试以正确的方式实施它。 –