【问题标题】:How to change drawable resource at run time? [duplicate]如何在运行时更改可绘制资源? [复制]
【发布时间】:2018-03-26 08:21:49
【问题描述】:

我想在运行时更改可绘制资源文件。

.java 文件代码

protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    btn = (Button)findViewById(R.id.button);
    edt1 = (EditText)findViewById(R.id.name);
    edt2 = (EditText)findViewById(R.id.password);
    str_name = edt1.getText().toString() ;
    str_password = edt2.getText().toString();

    if (str_name == 0 && str_password == 0) {
        btn.setBackgroundResource(R.drawable.image);
    }
    else {
        btn.setBackgroundResource(R.drawable.on_button_click);
    }

问题是它应用了if 条件,但是当我在EditText 中输入一些文本时,资源文件并没有改变。

EditText(s) 在TextInputLayout 之下。

【问题讨论】:

  • 你不能使用 == 比较字符串使用 .equals() 方法
  • 而且您甚至无法将对象与整数进行比较,就像您目前正在尝试做的那样。
  • 你可以查看我的答案。

标签: android android-textinputlayout


【解决方案1】:
  • 使用TextUtils.equals判断str_name是否等于0

  • 使用TextUtils.equals判断str_password是否等于0

试试这个。

protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    btn = (Button) findViewById(R.id.button);
    edt1 = (EditText) findViewById(R.id.name);
    edt2 = (EditText) findViewById(R.id.password);
    str_name = edt1.getText().toString();
    str_password = edt2.getText().toString();

    // edited here
    if (TextUtils.equals(str_name, "0") && TextUtils.equals(str_password, "0")) {
        btn.setBackgroundResource(R.drawable.image);
    } else {
        btn.setBackgroundResource(R.drawable.on_button_click);
    }
}

另一种解决方法。

if (Double.parseDouble(str_name) == 0 && Double.parseDouble(str_password) == 0) {
    btn.setBackgroundResource(R.drawable.image);
} else {
    btn.setBackgroundResource(R.drawable.on_button_click);
}

【讨论】:

    【解决方案2】:

    用下面的代码替换你的条件语句

    if (str_name.equalsIgnoreCase("0") && str_password.equalsIgnoreCase("0") {
    
        btn.setBackgroundResource(R.drawable.image);
    
    }
    

    您不能使用 == 来比较 2 个字符串。希望对你有所帮助。

    【讨论】:

    • 但在编辑文本中输入文本时没有更改按钮值
    • 将此答案与 EditText 的 addTextChangeListener 方法一起用于您的两个编辑文本,并将 abdul 的 waheed 代码放在 afterTextChanged 方法中。
    • @ChiragJain 谢谢伙计,它按我的要求工作得很好
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-10-04
    • 1970-01-01
    • 2023-03-19
    • 1970-01-01
    • 2020-06-17
    • 1970-01-01
    相关资源
    最近更新 更多