[英]How to create button in a widget, which change its color onClick?
我正在通過stackOverflow
和Internet進行搜索,但是找不到正確的信息。
當然,我知道什么是RemotViews
,這是正常活動中onClick
方法的基礎,但是在小部件中,它太復雜了。 我正在搜索類似: PendingIntent
, Intent
類的東西,但沒有找到任何東西。
問題/我要實現的目標:
在主屏幕小部件上,我有一個button
。 單擊時,我希望它的顏色發生變化,再次單擊它,我希望它被設置為初始顏色。 在進一步點擊時,我希望這種切換發生。
希望有人幫助我:)
在您的活動布局文件中,將button設置為
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:background="@color/white"
android:onClick="onClick"/>
默認使用白色作為背景。 然后在您的Java代碼中。
public void onClick(View view) {
ColorDrawable colorDrawable = (ColorDrawable)view.getBackground();
int buttonColor = colorDrawable.getColor();
if (buttonColor == R.color.white) {
view.setBackgroundColor(getResources().getColor(R.color.red));
} else {
view.setBackgroundColor(getResources().getColor(R.color.white));
}
}
每次您按下按鈕,都會交換顏色。
您應該嘗試使用選擇器可繪制的顏色狀態列表,並將其設置為按鈕的背景。
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:state_pressed="true"
android:color="#ffff0000"/> <!-- pressed -->
<item android:state_focused="true"
android:color="#ff0000ff"/> <!-- focused -->
<item android:color="#ff000000"/> <!-- default -->
</selector>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.