2011-10-04 129 views
4

我有一個小問題,那就是我現在使用切換按鈕,第一個切換按鈕用於白天或夜晚指示,第二個切換按鈕用於指示燈亮起或關閉。然後我的要求是當它是白天然後第二個切換按鈕不應該工作,然後當第二個切換按鈕應該工作,並且應該指示燈是否打開或關閉。而我的代碼是第一個切換按鈕不影響第二個

final ToggleButton tb = (ToggleButton) findViewById(R.id.togglebutton); 
     tb.setOnClickListener(new OnClickListener() 
{ 
public void onClick(View v) 
{ 
Toast.makeText(getBaseContext(), 
"Button is "+tb.getText().toString(), 
Toast.LENGTH_LONG).show(); 
if(tb.getText().toString().equals("ON")) 
{ 
final ToggleButton tb1= (ToggleButton) findViewById(R.id.togglebutton1); 
tb1.setOnClickListener(new OnClickListener() 
{ 
public void onClick(View v) 
{ 
Toast.makeText(getBaseContext(), 
"Button is "+tb1.getText().toString(), 
Toast.LENGTH_LONG).show(); 
}}); 
} 
else 
{ 
Toast.makeText(screen4.this,"It is day" , Toast.LENGTH_LONG).show(); 
finish(); 
} 
         } 
     }); 

任何人都可以幫助我使第二個按鈕不工作時,第一個按鈕關閉。在此先感謝

回答

2

這爲我工作:

<ToggleButton android:id="@+id/togglebutton" 
android:layout_width="150px" 
android:layout_height="50px" 
android:textOn="DAY" 
android:textOff="NIGHT" /> 
     <ToggleButton android:id="@+id/togglebuttontwo" 
android:layout_width="150px" 
android:layout_height="50px" 
android:textOn="ON" 
android:textOff="OFF" /> 

代碼:

 final ToggleButton tb = (ToggleButton) findViewById(R.id.togglebutton); 
    tb.setOnClickListener(new OnClickListener() { 
     public void onClick(View v) { 
      Toast.makeText(getBaseContext(), 
        "Button is " + tb.getText().toString(), 
        Toast.LENGTH_LONG).show(); 
      ToggleButton tbtwo = (ToggleButton) findViewById(R.id.togglebuttontwo); 

      if(tb.getText().equals("DAY")) 
      { 
       tbtwo.setEnabled(false); 
      } 
      else 
       tbtwo.setEnabled(true); 
     } 
    }); 

enter image description here

+0

喜裏諾,你怎麼你的切換按鈕上的漂亮的「*綠燈*」?我的只有一條。而且,你是如何獲得光滑外觀的? – Sam

1

試試這個。

final ToggleButton tb = (ToggleButton) findViewById(R.id.togglebutton); 
     tb.setOnClickListener(new OnClickListener() 
{ 
public void onClick(View v) 
{ 
Toast.makeText(getBaseContext(), 
"Button is "+tb.getText().toString(), 
Toast.LENGTH_LONG).show(); 
if(tb.getText().toString().equals("ON")) 
{ 
final ToggleButton tb1= (ToggleButton) findViewById(R.id.togglebutton1); 
tb1.setOnClickListener(new OnClickListener() 
{ 
public void onClick(View v) 
{ 
Toast.makeText(getBaseContext(), 
"Button is "+tb1.getText().toString(), 
Toast.LENGTH_LONG).show(); 
}}); 
} 
else 
{ 
Toast.makeText(screen4.this,"It is day" , Toast.LENGTH_LONG).show(); 
final ToggleButton tb1= (ToggleButton) findViewById(R.id.togglebutton1); 
tb1.setEnabled(false); 
finish(); 
} 
         } 
     }); 

代碼簡化版,在你所希望的方式工作,因爲,你得到的切換按鈕的refrence當它的夜晚,並設置其onClickListener,但在其他情況下,你什麼都不做,在這種情況下,Android將提供它的默認行爲就是唯一的原因。因此,在其他條件禁用它或者使它不Togglable什麼

相關問題