android中的setBackgroundDrawable

时间:2014-01-30 05:39:08

标签: android view drawable imagebutton

我想设置图像按钮的背景 drawable 。有两种方法(据我所知):setBackground和setBackgroundDrawable。我使用的是setBackground,它表示已在API级别16中添加,但我的项目是 min SDK version is 7 。为此我使用的是setBackgroundDrawable,但是它在api低于16的运行时没有更改drawable?这是我的代码片段

@TargetApi(Build.VERSION_CODES.JELLY_BEAN)
@SuppressWarnings("deprecation")

private void setVariable() {
        try {

        //change the bg for save button
        int sdk = android.os.Build.VERSION.SDK_INT;
        if(sdk < android.os.Build.VERSION_CODES.JELLY_BEAN) {
        //register.setBackground(getResources().getDrawable(R.drawable.btn_save));
                register.setBackgroundDrawable(getResources().getDrawable(R.drawable.btnsave));
            }else{
                register.setBackground(getResources().getDrawable(R.drawable.btn_save));
            }
            //register.setBackgroundDrawable(getResources().getDrawable(R.drawable.btn_save));
        } catch (Exception e) {
            // TODO: handle exception
    }
}

我应该使用什么?

3 个答案:

答案 0 :(得分:2)

使用register.setBackgroundResource(R.drawable.btn_save);

API级别1提供了

public void setBackgroundResource (int resid)

答案 1 :(得分:1)

在编写drawable的资源ID时你会犯错误 您使用 R.id.btnsave 代替 *&#39; R.drawable.btn_save&#39; *
否则,你的代码绝对正确!

答案 2 :(得分:1)

尝试以下方法:

btn.setBackgroundResource(R.drawable.new_todo_image);

并提供一些反馈

希望有所帮助。

相关问题