2011-10-04 117 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

我要去我的大學幾個講座,我會愛回到你身邊,並嘗試以正確的方式實施它。 –