2013-08-26 121 views
2

我希望我的圖像按鈕在每次點擊時從一個圖像更改爲另一個圖像。在我的代碼中,這隻能工作一次,圖像改變,按鈕不會改變onClick。每次點擊都會改變Android圖像按鈕

有人可以幫忙嗎?

package com.wepromoteme.brapp; 

import android.app.Activity; 
import android.os.Bundle; 
import android.view.View; 
import android.widget.ImageButton; 

public class MainActivity extends Activity { 

@Override 
protected void onCreate(Bundle savedInstanceState) { 
    super.onCreate(savedInstanceState); 
    setContentView(R.layout.activity_main); 

setupPlayPauseButton1(); 

} 

private void setupPlayPauseButton1() { 
    ImageButton btn1 = (ImageButton) findViewById(R.id.play_pause1); 

    btn1.setOnClickListener(new View.OnClickListener() { 

     @Override 
     public void onClick(View v) { 
      ImageButton btn1 = (ImageButton) 
findViewById(R.id.play_pause1); 
      btn1.setImageResource(R.drawable.play); 
     } 
    }); 
} 
} 

感謝

@ shree202

這是新代碼:

public class MainActivity extends Activity { 

@Override 
protected void onCreate(Bundle savedInstanceState) { 
    super.onCreate(savedInstanceState); 
    setContentView(R.layout.activity_main); 

setupPlayPauseButton1(); 

} 

private void setupPlayPauseButton1() { 
    final ImageButton btn1 = (ImageButton) findViewById(R.id.play_pause1); 

    btn1.setOnClickListener(new View.OnClickListener() { 

     @Override 
     public void onClick(View v) { 

      int i=0; 
      if(i%2==0) { 
       btn1.setImageResource(R.drawable.play); 
      } else { 
       btn1.setImageResource(R.drawable.pause); 

      } 
     } 
    }); 
} 
} 

感謝

+1

如果每次你點擊按鈕,圖像*總是*設置爲'R.drawable.play',我不希望圖像永遠改變爲別的東西。你認爲你應該如何處理這個問題(你一定想到了什麼)? –

+0

Inside onClick使用bt1.getBackground()獲取圖像背景並使用if else進行比較,然後更改背景。 –

回答

1

您應該擴展ImageButton並保持按鈕的狀態。所以它會改變你的點擊監聽器到這樣的事情:

@Override 
    public void onClick(View v) { 
     MyImageButton btn1 = (MyImageButton) findViewById(R.id.play_pause1); 
     btn1.toggleState(); 
     switch(btn1.getState()){ 
      case 0: 
       btn1.setImageResource(R.drawable.play); 
       break; 
      case 1: 
       bt1.setImageResource(R.drawable.stop); 
       break; 
     } 
    } 
+0

嘿,謝謝你,我按照你的例子推薦了我的代碼,但它仍然不起作用。你可以看一下嗎? – RobbieP14383

+0

'private void setupPlayPauseButton1(){ \t \t ImageButton btn1 =(ImageButton)findViewById(R.id.play_pause1); \t \t \t \t btn1.setOnClickListener(新View.OnClickListener(){ \t \t \t \t \t \t @Override \t \t公共無效的onClick(視圖v){ \t \t \t \t的ImageButton BTN1 =(的ImageButton)findViewById (R.id.play_pause1); \t \t btn1.toggleState(); \t \t s witch(btn1.getState()){ \t \t case 0: \t \t btn1.setImageResource(R.drawable.play); \t \t break; \t \t case 1: \t \t btn1.setImageResource(R.drawable.pause); \t \t break; \t \t} \t \t \t} \t \t}); \t}' – RobbieP14383

+0

錯誤是方法getState()未定義類型ImageButton toggleState和getState? – RobbieP14383