【问题标题】:How can I display a button in the onCreate method of an activity based on a given condition?如何根据给定条件在活动的 onCreate 方法中显示按钮?
【发布时间】:2021-05-01 11:26:23
【问题描述】:

我想在 Activity 中显示一个按钮,但如果用户满足特定条件,则按钮的文本和背景会有所不同。如何在 OnCreate 方法中初始化同一个按钮,根据条件有两种不同的设计?

【问题讨论】:

  • 通过执行初始化 Button button = view.findViewById(R.id.button); 根据条件更改背景和文本 if (conditionMet){ button.setText("Condition Met");} else { button.setBackground(getResources().getDrawable(R.drawable.whatever)}

标签: android android-activity android-button


【解决方案1】:

这里也许有帮助

 val btnGet = findViewById<Button>(R.id.btnGet)

    if (id == 1){   //Your condition 

        btnGet.text = id.toString()
        btnGet.visibility = View.VISIBLE    //Make Sure in xml it is gone 
        btnGet.setTextColor(Color.parseColor("#bdbdbd"))
        btnGet.setBackgroundColor(Color.parseColor("#ffffff"))
    }else{
        btnGet.text = id.toString()
         btnGet.visibility = View.VISIBLE
        btnGet.setTextColor(Color.parseColor("#FFBB86FC"))
        btnGet.setBackgroundColor(Color.parseColor("#FF03DAC5"))

    }

如果你想要完整的代码,我会与你分享 快乐编码

【讨论】:

    【解决方案2】:

    1。您可以在运行时更改此属性。

    2。您可以创建两个可绘制文件以在按钮背景中进行设置,但您仍需要在运行时更改文本。

    3。您可以使用布局数据在 xml 文件中使用数据绑定,例如: Google Link

    【讨论】:

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