簡體   English   中英

根據當前背景更改按鈕的背景

[英]Changing background of button depending on current background

我試圖在單擊按鈕時更改其背景,但也能夠在再次單擊該按鈕時將其更改回。 我想做的是獲取按鈕的當前背景,如果是(xxxxx),則將其更改為(yyyyy)。 我似乎找不到如何獲取按鈕的當前背景並將其與我的可繪制資源之一進行比較的方法。
任何幫助將非常感激。

我正在嘗試做的一些偽代碼:

if (button1.getBackground() == R.drawable.someDrawable) {
   button1.setBackgroundResource(R.drawable.someOtherDrawable);
}

我認為這是正確的方法: 鏈接

我的簡單解決方案是將兩個可繪制對象用作背景。 一個用於non_pressed_selector和Pressed_selector,只要跟蹤是否按下按鈕就可以了。

private boolean isPressed = false;
public void onClick() {
    if (isPressed) {
        // set not_pressed_selector
    } else {
        // set pressed_selector
    }
    isPressed != isPressed;
}

我所做的是:

在初始狀態下聲明按鈕:

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

然后,我通過代碼管理帶有標簽的按鈕的實際狀態的事件:

protected void onCreate(Bundle savedInstanceState)
{
    super.onCreate(savedInstanceState);
    setContentView(R.layout.drawables_buttons);  //This is the layout where it's the button

    threeStateButton = (Button)findViewById(R.id.three_States_Button);  //This is the button
    threeStateButton.setOnTouchListener(new CustomTouchListener());    
    threeStateButton.setTag("StateA");    //Set the control tag
}

private class CustomTouchListener implements View.OnTouchListener
{

    @Override
    public boolean onTouch(View view, MotionEvent motionEvent)
    {
        switch (motionEvent.getAction())
        {
            case MotionEvent.ACTION_UP:  //When you lift your finger
                if (threeStateButton.getTag().equals("StateA"))
                {
                    threeStateButton.setBackgroundResource(R.drawable.StateB);
                    Toast.makeText(view.getContext(), "This gonna change my state from StateA to StateB",Toast.LENGTH_SHORT).show();
                    threeStateButton.setTag("StateB");
                }
                else  //If when you lift your finger it was already on stateB
                {
                    threeStateButton.setBackgroundResource(R.drawable.red_button);
                    Toast.makeText(view.getContext(), "This gonna change my state from StateB to StateA",Toast.LENGTH_SHORT).show();
                    threeStateButton.setTag("StateA");
                }
                break;
            //In case you want that you button shows a different state when your finger is pressing it.
            case MotionEvent.ACTION_DOWN:
                threeStateButton.setBackgroundResource(R.drawable.StateButtonPressed);
                break;
        }

        return false;
    }
}

我不知道這是否是最好的方法,但它確實有效,是的,我想知道這是最佳方法。

似乎您需要一個ToggleButton而不是簡單的Button 您可以使用isChecked()方法確定OnClickListener按鈕的狀態,並在OnClickListener設置背景。 或者您可以在xml中定義選擇器,如pedr0所述。

暫無
暫無

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

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