【问题标题】:Android getBackground安卓获取背景
【发布时间】:2020-04-18 08:36:01
【问题描述】:

我想有一个按钮,如果你点击它,它会设置背景,但如果背景已经设置,它会做其他事情。目前这是我的代码,但我似乎无法让它工作

if (view.background == R.drawable.frog) {
         //do stuff
} else {
         //other stuff
}

【问题讨论】:

    标签: android button kotlin background


    【解决方案1】:

    您可以尝试: 使用 Kotlin:

    val bgAlready = btnTest.background.constantState == ContextCompat.getDrawable(this, R.drawable.frog)?.constantState
                if (!bgAlready) {
                    btnTest.background = ContextCompat.getDrawable(this, R.drawable.frog)
                } else {
                    //other stuff
                }
    

    使用 Java:

    boolean bgAlready = btnTest.getBackground().getConstantState() == 
                            ContextCompat.getDrawable(TestActivity.this, R.drawable.frog).getConstantState();
                    if (!bgAlready) {
                        btnTest.setBackground(ContextCompat.getDrawable(TestActivity.this, R.drawable.frog)); 
                    } else {
                        //other stuff
                    }
    

    【讨论】:

      【解决方案2】:

      这很有帮助

      val drawable = ContextCompat.getDrawable(getContext(), R.drawable.frog)
      if(view.background.constantState?.equals(drawable?.constantState) == true) {
           //do stuff
      } else {
           //other stuff
      }
      

      【讨论】:

        【解决方案3】:

        如果它为空,则检查它是否为空,否则它未设置,否则背景已设置。

        if (view.background == null) {
             //do stuff
        } else {
             //other stuff
        }
        

        希望对你有帮助。

        【讨论】:

          猜你喜欢
          • 2011-10-10
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多