禁止和恢复按钮

该文章讲述了如何在Android中使用`android:enabled`属性控制Button的启用和禁用状态。通过设置该属性的值为true或false,可以控制按钮是否可被点击。同时,文中展示了XML布局代码和Java代码片段,用于实现按钮的启用和禁用功能,以及处理点击事件更新TextView的内容。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

对于Button是否允许按钮,需引入android:enabled,当属性值为rue时,则允许点击按钮;当属性值为false时,则禁止按钮点击。

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical">
    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="horizontal">
        <Button
            android:id="@+id/btn_enable"
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:text="启用测试按钮" />
        <Button
            android:id="@+id/btn_disable"
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:text="禁用测试按钮" />
    </LinearLayout>
    <Button
        android:id="@+id/btn_test"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:enabled="false"
        android:text="测试按钮"
        android:textColor="#888888"
        android:textSize="17sp" />
    <TextView
        android:id="@+id/tv_result"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:paddingLeft="5dp"
        android:text="这里查看测试按钮的点击结果" />
</LinearLayout>
findViewById(R.id.btn_enable).setOnClickListener(this);
    findViewById(R.id.btn_disable).setOnClickListener(this);
    tv_result = findViewById(R.id.tv_result);
    btn_test = findViewById(R.id.btn_test);
    btn_test.setOnClickListener(this);
}
@Override
public void onClick(View v) {
    if (v.getId() == R.id.btn_enable) {
        btn_test.setEnabled(true); // 启用当前控件
    } else if (v.getId() == R.id.btn_disable) {
        btn_test.setEnabled(false); // 禁用当前控件
    } else if (v.getId() == R.id.btn_test) {
        String desc = String.format("您点击了按钮:%s", ((Button)v).getText());
        tv_result.setText(desc); // 设置文本视图的文本内容
    }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

当当2000

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值