16岁以下的API是否存在类似setBackground的方法?

时间:2014-01-03 10:09:19

标签: java android api button background

当我点击安排这样的解决方案时,我试图更改自定义按钮:

...

    final Button button1 = (Button) findViewById(R.id.button1);
    boolean i1 = false;

...

        View.OnClickListener gestore = new View.OnClickListener() {
          public void onClick(View view) {

                Resources res = getResources();
                Drawable shape = res. getDrawable(R.drawable.round_shape);
                Drawable shape_clicked = res. getDrawable(R.drawable.round_shape_clicked);


            switch(view.getId()){

              case R.id.button1:

                  i1 = !i1;
                  button1.setBackground(i1 == true ? shape_clicked : shape);  
                break;

              case R.id.button2:

                  i2 = !i2;
                  button2.setBackground(i2 == true ? shape_clicked : shape);  
                break;

不幸的是我发现这个方法(setBackground)仅适用于API 16。 如何使用较低的API设法做同样的事情? 谢谢你的回答,抱歉我的英文不好

2 个答案:

答案 0 :(得分:1)

int build = android.os.Build.VERSION.SDK_INT; 
if(build < android.os.Build.VERSION_CODES.JELLY_BEAN)
{
    setBackgroundDrawable(i1 == true ? shape_clicked : shape);
}
else
{
    setBackground(i1 == true ? shape_clicked : shape);
}

答案 1 :(得分:0)

您还可以使用: button.setBackgroundResource(resid)喜欢:

int build = android.os.Build.VERSION.SDK_INT; 
if(build < android.os.Build.VERSION_CODES.JELLY_BEAN)
{
       button1.setBackgroundResource(i1 == true ? R.drawable.round_shape : R.drawable.round_shape_clicked);
}
else
{
       button1.setBackground(i1 == true ? shape_clicked : shape);
}