如何在 Activity class 中启用 xml 按钮?

How to enable xml Button in a Activity class?

我的 top_navigation_menu 布局中有这个项目我想以编程方式在我的 OnCreate 方法中启用它:

    <item
    android:id="@+id/action_button"
    android:enabled="false"
    android:visible="false"
    android:clickable = "false" />

示例:当用户打开新文件时 Activity 启用此项目。

编辑:这是我的 的跟进,所以我正在尝试另一种方法。

编辑:经过一些研究,我发现

   Button btn = (Button) findViewById(R.id.action_button);
    btn.setEnabled(true);
    btn.setClickable(true);

不确定我应该使用哪一个

在你的 xml 而不是 "item" 中使用 "Button"

在 onCreate() 中:

Button button = (Button) findViewById(R.id.action_button);
button.setVisibility(View.VISIBLE);
button.setEnabled(true); 

我对你想要达到的目标感到困惑。 Visible, clickable 和 enable 是相同的组件属性状态,但输出不同

  1. visible is your button visibility if you set it value to false it gonna be gone and clear the Rect from the screen also
  2. enable it's mean prevents the user from tapping the Button. The appearance of enabled and non-enabled Button may differ, if the drawables referenced
  3. clickable it's mean how your Button reacts to click events. false mean disable the click events

我看到的是你试图把它们都放上来,这对我来说很糟糕。一种状态就足够了,具体取决于您要实现的目标。这是示例和我的建议:

  1. 启用状态,XML:

    <Button
        android:id="@+id/action_button"
        android:enabled="false"/>
    
  2. 可见状态,XML:

    <Button
        android:id="@+id/action_button"
        android:visible="false"/>
    
  3. 可点击状态,XML:

    <Button
        android:id="@+id/action_button"
        android:clickable="false"/>
    

然后从你的OnCreate你可以改变他们的状态如下

Button myButton = findViewById(R.id.action_button);
//for visibility state
myButton.setVisibility(View.VISIBLE);
//for enable state
myButton.setEnable(true);
//for clickable state
myButton.setClickable(true);