【问题标题】:How to disable a button in onCreate method with if statment [duplicate]如何使用 if 语句禁用 onCreate 方法中的按钮 [重复]
【发布时间】:2017-07-17 17:52:31
【问题描述】:

我有一个问题,我想在onCreate方法中禁用一个按钮,请分享在onCreate方法中在运行时禁用任何按钮的方法。

 @Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_requests_interface);


  Intent intent = new Intent(this, AdminPopup.class);
    startActivity(intent);


    String fName = getIntent().getStringExtra("fName");
    TextView tfName = (TextView)findViewById(R.id.fName);
    tfName.setText(fName);
    String vuEmail = getIntent().getStringExtra("VUEmail");
    TextView tEmail = (TextView)findViewById(R.id.vuEmail);
    tEmail.setText(vuEmail);

    EditText vuEmailTest = (EditText)findViewById(R.id.vuEmail);
    String email = vuEmailTest.getText().toString();
    String str = email.substring(0,2);
    if(str.equals("bc")){
        String str2 = email.substring(3,9);
        boolean digitsOnly = TextUtils.isDigitsOnly(str2);
        if (digitsOnly){
            Button accButton = (Button)findViewById(R.id.accButton);

        }
    }
    else{
        Button accButton = (Button)findViewById(R.id.accButton);

    }

}

【问题讨论】:

  • 在布局中将其设置为禁用。因此,当您通过setContentView() 添加它时,您会发现它已被禁用。通过这样做,您将不需要任何额外的代码。除了以后重新启用它。
  • 你可以通过xml使用enbale属性来禁用它。

标签: java android android-layout disabled-control fragment-oncreateview


【解决方案1】:

按钮按钮 =(Button) findViewById(R.id.buttonid); button.setVisibility(View.GONE);

【讨论】:

    【解决方案2】:

    试试这个:

        Button accButton = (Button) findViewById(R.id.accButton);
        accButton.setEnabled(false);
    

    请注意,在您发布的代码中,您将按钮设置为findViewbyId(),应为findViewById()(By 需要大写)。

    【讨论】:

    • 我可以在 onCreate 方法中使用 if 语句吗?因为我必须进行一些检查,然后必须禁用按钮
    • 当然。或者你可以写类似accButton.setEnabled(check1 && check2);
    • 它只是在放入 if 语句后给出运行时错误
    【解决方案3】:

    在 xml 中使用 android:enabled="false" 或在代码中使用 accButton.setEnabled(false)
    此外,最好通过这种方法检查是否为数字:

    public static boolean isNumeric(String str) {
        try {
            double d = Double.parseDouble(str);
        } catch (NumberFormatException nfe) {
            return false;
        }
        return true;
    }
    

    【讨论】:

    • 我可以在 onCreate 方法中使用 if 语句吗?因为我必须进行一些检查,然后必须禁用按钮
    • @bs140200456AqsaAnum 是的,为什么不
    • 我刚刚输入了 if 语句,现在它给出了运行时错误
    • @bs140200456AqsaAnum 包括你的 if 语句
    • 我可以编辑上面的代码吗?如何,我会把我当前的代码放在那里
    【解决方案4】:

    这样做:

    Button b = (Button) findViewById(R.id.mybutton);
    b.setEnabled(false);
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-02-15
      • 1970-01-01
      • 2021-07-03
      • 1970-01-01
      • 2018-07-29
      • 2017-04-01
      相关资源
      最近更新 更多