回复
TextField换行实现以及按回车键换行实现
charlesc
发布于 2021-3-25 09:49
浏览
0收藏
今天又有坛友问到TextField换行怎么实现,我来分享一下实现代码吧,首先看布局页面,代码如下
<?xml version="1.0" encoding="utf-8"?>
<DependentLayout
xmlns:ohos="http://schemas.huawei.com/res/ohos"
ohos:height="match_parent"
ohos:width="match_parent"
ohos:orientation="vertical">
<TextField
ohos:id="$+id:txtNumber"
ohos:height="300vp"
ohos:width="500vp"
ohos:background_element="#AFEEEE"
ohos:align_parent_top="true"
ohos:text_size="20vp"
ohos:bubble_height="0"
ohos:right_margin="20vp"></TextField>
<Button
ohos:id="$+id:btnNewLine"
ohos:height="match_content"
ohos:width="match_content"
ohos:background_element="#FFE4B5"
ohos:text_size="50vp"
ohos:text="换行"
ohos:right_of="$id:txtNumber"
ohos:bottom_margin="30vp"/>
<Button
ohos:id="$+id:btnGetText"
ohos:height="match_content"
ohos:width="match_content"
ohos:background_element="#FFE4B5"
ohos:text_size="50vp"
ohos:text="获取文本"
ohos:right_of="$id:txtNumber"
ohos:below="$id:btnNewLine"/>
</DependentLayout>
然后我们看一下布局页面运行效果如下图
这个布局页面使用相对布局,布局很简单就是一个TextField和两个按钮,因为会涉及到换行所以我将TextField的高度和宽度设置的很大,特别是高度,这样方便查看效果。这里注意一下每次光标落下去会悬浮自带的圆圈光标,可以通过设置bubble_height为0,不然显示着有点不爽。
然后我们看一下Java实现代码,如下
package com.example.tvtest.slice;
import com.example.tvtest.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.hiviewdfx.HiLog;
import ohos.hiviewdfx.HiLogLabel;
import ohos.multimodalinput.event.KeyEvent;
public class TextFieldTestSlice extends AbilitySlice {
static final HiLogLabel label=new HiLogLabel(HiLog.LOG_APP,0x0001,"回车换行测试");
@Override
public void onStart(Intent intent) {
super.onStart(intent);
super.setUIContent(ResourceTable.Layout_ability_text_field_test);
HiLog.info(label,"程序启动了");
TextField txtNumber = (TextField) findComponentById(ResourceTable.Id_txtNumber);
txtNumber.setKeyEventListener((c,k)->{
HiLog.info(label,"按键事件触发");
if(c.hasFocus())
{
//如果不增加该判断则会触发两次
if(k.isKeyDown()){
HiLog.info(label,"回车键按下");
if(k.getKeyCode()==k.KEY_ENTER)
{
String val=txtNumber.getText();
txtNumber.setText(val+"\n"+"888");
HiLog.info(label,"按了回车键");
}
}
}
return false;
});
Button btnGetText=(Button)findComponentById(ResourceTable.Id_btnGetText);
btnGetText.setClickedListener(c->{
HiLog.info(label,"获取文本点击");
HiLog.info(label,"文本内容"+txtNumber.getText());
});
Button btnNewLine=(Button)findComponentById(ResourceTable.Id_btnNewLine);
btnNewLine.setClickedListener(c->{
//代码触发换行
txtNumber.setText(txtNumber.getText()+"\n"+"123456");
});
}
@Override
public void onActive() {
super.onActive();
}
@Override
public void onForeground(Intent intent) {
super.onForeground(intent);
}
}
这里要注意一下一定要使用KeyEvent.isKeyDown,不然会触发两次!!! 换行符号就是\n
下面看一下运行效果,如下图
大家可以自己好好测试效果
分类
标签
已于2021-3-25 09:49:48修改
赞
收藏
回复
相关推荐