2014-06-27 57 views
0

我有imagebutton,我想用toggle開關(如toggleButton)編寫setOnClickListener方法。我知道如何使用togglebutton,但我不需要使用它。這是一個可能的寫在圖像按鈕toggleclick方法。我寫了一些代碼,但不工作,如切換按鈕Android imagebutton toggle點擊

strada_chart.setOnClickListener(new OnClickListener() { 

     @Override 
     public void onClick(View arg0) { 
      if(arg0.isClickable()==true) 
      { 
       Toast.makeText(getApplicationContext(), "1", Toast.LENGTH_SHORT).show(); 
      } 
      else 
      { 
       Toast.makeText(getApplicationContext(), "2", Toast.LENGTH_SHORT).show(); 
      } 
     } 
    }); 
+0

切換?像複選框? – Blackbelt

+0

like toggleButton – user3775061

回答

1

試試這個..

Like_btn.setOnClickListener(new OnClickListener() 
     { 

      public void onClick(View v) 
      { 
       if(fun) 
       { 
       Like_btn.setImageResource(R.drawable.unlike); 
       fun=false; 
       } 
       else 
       { 
        fun=true;  
        Like_btn.setImageResource(R.drawable.like); 
        Toast.makeText(getApplicationContext(), "Changed", Toast.LENGTH_LONG).show(); 
       } 
      } 
     }); 
+0

在你的代碼中fun是一個布爾類型,第一次fun = false? – user3775061

+0

是的,它也是靜態的 – Giridharan

0
public void onToggleClicked(View view) { 
     // Is the toggle on? 
     switch (view.getId()) { 
     case R.id.xyz: 
      boolean on = ((ToggleButton) view).isChecked(); 

      if (on) { 


       Toast.makeText(mContext, "A", Toast.LENGTH_SHORT).show(); 
      } else { 


       Toast.makeText(mContext, "B", Toast.LENGTH_SHORT).show(); 
      } 
     } 
    } 

切換按鈕

的使用屬性在XML:

<ToggleButton 
      android:id="@+id/xyz" 
      style="@style/toggleButton" 
      android:layout_width="190dp" 
      android:layout_height="50dp" 
      android:layout_gravity="center_vertical|center_horizontal" 
      android:layout_margin="8dp" 
      android:background="@drawable/ic_toggle_sv" 
      android:onClick="onToggleClicked" /> 

在ic_toggle_sv

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

    <item 
     android:id="@+android:id/background" 
     android:drawable="@android:color/transparent"/> 
    <item 
     android:id="@+android:id/toggle" 
     android:drawable="@drawable/ic_toggle1"/> 

</layer-list> 

在ic_toggle1通過切換按鈕

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

    <item android:drawable="@drawable/ic_toggle_stills" android:state_checked="false"/> 
    <item android:drawable="@drawable/ic_toggle_videos" android:state_checked="true"/> 

</selector> 
0

試試這兩者的圖像....

private static boolean isClicked = true; 
strada_chart.setOnClickListener(new OnClickListener() { 

    @Override 
    public void onClick(View arg0) { 
     if(isClicked) 
     { 
      Toast.makeText(getApplicationContext(), "1", Toast.LENGTH_SHORT).show(); 
      isClicked = false; 
     } 
     else 
     { 
      Toast.makeText(getApplicationContext(), "2", Toast.LENGTH_SHORT).show(); 
     } 

    } 
});