簡體   English   中英

在android中單擊時imageView不變

[英]imageView not changed when clicked in android

我已經在android中制作了一個簡單的自定義復選框程序,因為我想根據用戶操作更改兩個圖像的“ difault”和“ checked”狀態,所以我想更改該圖像..我嘗試了以下無效的代碼,

在此處輸入圖片說明

我的代碼是:

final ImageView chekbx =(ImageView)dialog.findViewById(R.id.chk_login);
            if(chekbx.isSelected()){
                System.out.println("checkbox check");
                chekbx.setBackgroundResource(R.drawable.checkbox_ticked);
            }else{
                chekbx.setBackgroundResource(R.drawable.checkbox);
            }

為此使用選擇器。

這是您的checkboc:

          <CheckBox
            android:id="@+id/remb_ckh_box"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:button="@drawable/check_box_selector" />

及其選擇器:

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

<item android:state_checked="true" android:drawable="@drawable/checkbox_selected" />

<item android:state_checked="false" android:drawable="@drawable/checkbox_unselected" />

</selector>

嘗試使用以下代碼:

已編輯

final ImageView chekbx =(ImageView)dialog.findViewById(R.id.chk_login);
boolean flag =false; //TAKE AS A PUBLIC VAR
chekbx.setOnClickListener(new OnClickListener() {
    @Override
    public void onClick(View v) {
        // TODO Auto-generated method stub
        if(flag)
        {
            chekbx.setBackgroundResource(R.drawable.checkbox);
            flag=false;
        }
        else
        {
            System.out.println("checkbox check");
            chekbx.setBackgroundResource(R.drawable.checkbox_ticked);
            flag = true;
        }
    }
});

希望這會幫助你。

Android已經具有CheckBox視圖,您無需自己構建一個。

復選框API: http : //developer.android.com/reference/android/widget/CheckBox.html

此復選框也可以使用選擇器來包含自定義圖像: 如何更改CheckBox的默認圖像

    void onClick Login(View v)
    {
        if(checkbx.isSelected(){
            chekbx.setBackgroundResource(R.drawable.checkbox_ticked);
            <Set your new database with login details and phone ID to remember>
            //check your database for login details here with registered details
            }
        else{
            chekbx.setBackgroundResource(R.drawable.checkbox);
            //check your database for login details here with registered details
        }
    }   

這種邏輯應該可以為您提供幫助。 謝謝。

暫無
暫無

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

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