change checkbox background color in android

前端 未结 6 991
一向
一向 2020-12-15 08:31

i have to develop one app.here i have to use checkbox.here i have to select checkbox means the default background color is yellow.but i wish to change the background

6条回答
  •  误落风尘
    2020-12-15 09:16

    try this code

    public class MainActivity extends Activity {
    
    CheckBox box;
    boolean flag=false;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
    
        box=(CheckBox)findViewById(R.id.box);
    
        box.setOnClickListener(new OnClickListener() {
    
            @Override
            public void onClick(View arg0) {
                // TODO Auto-generated method stub
    
                if(flag){
                    GradientDrawable d=new GradientDrawable();
                    d.setColor(Color.RED);
                    box.setBackgroundDrawable(d);
                    }
                else{
                    GradientDrawable d=new GradientDrawable();
                    d.setColor(Color.GREEN);
                    box.setBackgroundDrawable(d);
                }
                flag=!flag;
                }
    
        });
    }
    

    }

提交回复
热议问题