簡體   English   中英

如何更改按鈕背景色作為單擊動作?

[英]how to change button background color as clicked action?

-在android應用程序中-

單擊按鈕后,其背景色更改為必填。 再次單擊,其顏色將恢復原始顏色。

如何執行呢?

任何回應,謝謝!

================================================== ================================更新:從網絡上,我找到了一種實現這一目標的方法。 在xml中設計可繪制顏色,如下所示:

<drawable name="button_checked">#ffff0000</drawable>  

在活動中,使用以下代碼獲取Drawable對象:

Resources resource = getBaseContext().getResources();
checked_drawable = resource.getDrawable(R.drawable.button_checked);

在onClick函數中,根據布爾變量:

 setBackgroundDrawable(checked_mDrawable)

設置按鈕背景。

在你的js文件中

$('#button')。toggleClass('bg');

在您的CSS中,使用常規的按鈕CSS樣式

#button { background: white; }

然后添加

#button.bg { background: red; }

因此,當他們單擊按鈕時,它將變成紅色的背景,如果再次單擊它,它將變成白色。

使用任何想要的背景顏色/網址。

您只需要創建一個狀態列表可繪制資源,如下所示:

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

    <item android:drawable="@drawable/btn_login_pressed" android:state_pressed="true"/>
    <item android:drawable="@drawable/btn_login_normal" android:state_pressed="false"/>

</selector>

更新:也許您希望將效果用作RadioButton,這是一個示例:

    <RadioButton
       android:id="@+id/tab_communication"
       android:layout_width="wrap_content"
       android:layout_height="40dp"
       android:layout_weight="1"
       android:background="@null"
       android:button="@null"
       android:drawableTop="@drawable/category_communication"
       android:paddingBottom="5dp"
       android:paddingTop="5dp" />

drawable / category_communication.xml:

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

    <item android:drawable="@drawable/category_communication_checked" android:state_checked="true"/>
    <item android:drawable="@drawable/category_communication_normal" android:state_checked="false"/>

 </selector>

ToggleButton是另一個選擇。

您可以在代碼中動態地做到這一點(我不知道如何在xml中配置它)。

boolean flag=true;
Button button=(Button)findViewById(R.id.button);
oncreate()
{
    button.setBackgroundResource(R.drawable.first_time_click);
    button.setOnClickListener(new OnClickListener()
    {
    public void onClick(View v)
    {
        if (flag)
        {
            button.setBackgroundResource(R.drawable.odd_time_click);        
        }else
        {
           button.setBackgroundResource(R.drawable.even_time_click);
        }
        flag=!flag;
    }
    });
}

暫無
暫無

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

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