HarmonyOS开发32:TextField练习1——密码明文密文切换

鸿蒙开发 专栏收录该内容
58 篇文章 12 订阅

添加一个按钮,按住不松是明文,松开是密文

ability_main.xml代码:

<?xml version="1.0" encoding="utf-8"?>
<DirectionalLayout
    xmlns:ohos="http://schemas.huawei.com/res/ohos"
    ohos:height="match_parent"
    ohos:width="match_parent"
    ohos:orientation="vertical"
    ohos:background_element="#F2F2F2"
    >

    <TextField
        ohos:id="$+id:text"
        ohos:height="50vp"
        ohos:width="319vp"
        ohos:hint="请输入密码"
        ohos:text_size="17fp"
        ohos:hint_color="#999999"
        ohos:text_alignment="center"
        ohos:top_margin="100vp"
        ohos:layout_alignment="horizontal_center"
        ohos:background_element="#FFFFFF"
        ohos:text_input_type="pattern_password"
        />

    <Button
        ohos:id="$+id:but"
        ohos:height="47vp"
        ohos:width="319vp"
        ohos:text="查看密码"
        ohos:text_size="24fp"
        ohos:text_color="#FEFEFE"
        ohos:text_alignment="center"
        ohos:background_element="#21A8FD"
        ohos:top_margin="77vp"
        ohos:layout_alignment="center"
        />

</DirectionalLayout>

MainAbilitySlice.java代码:

package com.example.textfieldapplication.slice;

import com.example.textfieldapplication.ResourceTable;
import ohos.aafwk.ability.AbilitySlice;
import ohos.aafwk.content.Intent;
import ohos.agp.components.Button;
import ohos.agp.components.Component;
import ohos.agp.components.InputAttribute;
import ohos.agp.components.TextField;
import ohos.multimodalinput.event.TouchEvent;

public class MainAbilitySlice extends AbilitySlice implements Component.TouchEventListener
{
    TextField tf;
    @Override
    public void onStart(Intent intent) {
        super.onStart(intent);
        super.setUIContent(ResourceTable.Layout_ability_main);

        //1.找到组件

        tf = (TextField) findComponentById(ResourceTable.Id_text);
        Button but = (Button) findComponentById(ResourceTable.Id_but);

        //2.给按钮绑定触摸事件(滑动事件):长按不松的过程
        but.setTouchEventListener(this);
    }

    @Override
    public void onActive() {
        super.onActive();
    }

    @Override
    public void onForeground(Intent intent) {
        super.onForeground(intent);
    }

    @Override
    public boolean onTouchEvent(Component component, TouchEvent touchEvent) {
        int action = touchEvent.getAction();
        if (action == TouchEvent.PRIMARY_POINT_DOWN){   //按下不松,变明文
            tf.setTextInputType(InputAttribute.PATTERN_NULL);
        }else if (action == TouchEvent.PRIMARY_POINT_UP){    //松开,变密文
            tf.setTextInputType(InputAttribute.PATTERN_PASSWORD);
        }
        return true;
    }
}

效果:
请添加图片描述

  • 1
    点赞
  • 0
    评论
  • 0
    收藏
  • 一键三连
    一键三连
  • 扫一扫,分享海报

©️2021 CSDN 皮肤主题: 技术黑板 设计师:CSDN官方博客 返回首页
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值