簡體   English   中英

單擊時更改android按鈕圖標

[英]android change button icon when clicked

我想知道在點擊按鈕圖像時是否有更改按鈕圖像的方法。 最初,按鈕有一個暫停圖標。 單擊它時,我希望顯示播放圖標。 每次單擊該按鈕時,圖標應在播放和暫停之間變化。

有沒有辦法做到這一點?

XML布局文件:

<ImageButton
    android:id="@+id/play"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_alignParentTop="true"
    android:layout_centerHorizontal="true"
    android:layout_marginTop="109dp"
    android:src="@drawable/play_btn"
    android:background="@null" />

play_btn.xml

<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:drawable="@drawable/pause" android:state_selected="true" />
    <item android:drawable="@drawable/play" />
</selector>

帶有自定義選擇器的Android's Toggle Button聽起來就像你想要的那樣。

你可以使用這樣的東西作為按鈕的選擇器:

<selector xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:drawable="@drawable/play_icon" android:state_checked="true" />
    <item android:drawable="@drawable/pause_icon" android:state_checked="false" />
</selector>

讓我們在你的布局中為你的按鈕的xml添加一個onClick字段(需要API級別4及以后)

<ImageButton
    android:id="@+id/play"
    ...
    android:onClick="buttonPressed" />

您的圖標是可繪制的pauseplay

跟蹤按鈕的圖標。

private boolean paused = true;

public void buttonPressed(View view) {

    ImageButton button = (ImageButton) view;
    int icon;

    if (paused) {
        paused = false;
        icon = R.drawable.pause;
    else {
        paused = true;
        icon = R.drawable.play;
    }

    button.setImageDrawable(
        ContextCompat.getDrawable(getApplicationContext(), icon));


}
Button mPlayButton;

boolean isPlay = false;
@Override
public void onCreate(){
    mPlayButton = (Button) findViewById(R.id.play);
    // Default button, if need set it in xml via background="@drawable/default"
    mPlayButton.setBackgroundResource(R.drawable.default);
    mPlayButton.setOnClickListener(mTogglePlayButton);
}

View.OnClickListener mTogglePlayButton = new View.OnClickListener(){

    @Override
    public void onClick(View v){
        // change your button background

        if(isPlay){ 
            v.setBackgroundResource(R.drawable.default);
        }else{
            v.setBackgroundResource(R.drawable.playing);
        }

        isPlay = !isPlay; // reverse
    }

};

查看此文檔http://developer.android.com/reference/android/widget/ImageButton.html特別是android.widget.imageview中繼承的方法。 您將要使用setImageBitmap或setImageDrawable。 將其更新為點擊代碼的一部分。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM