android 编码实用技巧(持续更新ing)

1、设定listview中item的高度

通过layout_height属性设置高度无效,需要设置minHeight属性

2、singleLine = true与maxLines=1的区别

maxLines: Makes the TextView be at most this many lines tall.
singleLine:Constrainsthe text to a single horizontally scrolling line instead of letting it wrap onto multiple lines, and advances focus instead of inserting a newline when you press the enter key.

使用maxLines为1时,仅限制高度。按下enter键,输入框中出现"\n",显示换行效果
使用singleLines为ture,配合EditText的imeOption=“actionSearch”可以将enter键变为“搜索”键。

但目前singleLines方法已过时,可使用lines=“1”代替

3、Fragment中的context对象

Fragment中this对象获取的是Fragment的context,当直接使用该context.startActivity(intent)时会出现运行时异常,提示从非activity中启动activity,需要使用FLAG_ACTIVITY_NEW_TASK属性
解决方案:1)使用getActivity()获取容器activity的context对象,用来启动其他的activity对象
2)使用Intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);

4、INVISIBLE对象的OnClickListener事件

针对INVISIBLE的view对象,设置setOnClickListener之后,点击隐藏的view区域,仍会触发该事件。这个时候需要使用view.setOnClickListener(null)来取消事件处理。

5、设置EditText的hint的位置

默认情况,hint居中。可以通过android:gravity="top|left"来将hint显示在左上角。

6、ImageView的background和src属性

在开发中遇到设置ImageView的src后,出现了图像重叠的问题。排查后发现layout文件的ImageView中设置了background属性,而代码中使用glide设置了src属性,导致图像重叠。
解决方案:统一采用background或者src属性。
对应的java代码

//设置background
imageView.setBackgroundResource(R.drawable.***)
//设置src
imageView.setImageResource(R.drawable.***)

7、设置EditText的输入限制

可以设置inputType属性,可选值如下:

android:inputType=”none”
android:inputType=”text”
android:inputType=”textCapCharacters” 字母大写
android:inputType=”textCapWords” 首字母大写
android:inputType=”textCapSentences” 仅第一个字母大写
android:inputType=”textAutoCorrect” 自动完成
android:inputType=”textAutoComplete” 自动完成
android:inputType=”textMultiLine” 多行输入
android:inputType=”textImeMultiLine” 输入法多行(如果支持)
android:inputType=”textNoSuggestions” 不提示
android:inputType=”textUri” 网址
android:inputType=”textEmailAddress” 电子邮件地址
android:inputType=”textEmailSubject” 邮件主题
android:inputType=”textShortMessage” 短讯
android:inputType=”textLongMessage” 长信息
android:inputType=”textPersonName” 人名
android:inputType=”textPostalAddress” 地址
android:inputType=”textPassword” 密码
android:inputType=”textVisiblePassword” 可见密码
android:inputType=”textWebEditText” 作为网页表单的文本
android:inputType=”textFilter” 文本筛选过滤
android:inputType=”textPhonetic” 拼音输入
//数值类型
android:inputType=”number” 数字
android:inputType=”numberSigned” 带符号数字格式
android:inputType=”numberDecimal” 带小数点的浮点格式
android:inputType=”phone” 拨号键盘
android:inputType=”datetime” 时间日期
android:inputType=”date” 日期键盘
android:inputType=”time” 时间键盘

也可以设置digits限制输入字符,如只能输入数字和英文

android:digits="0123456789abcdefghigklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"

你可能感兴趣的:(android 编码实用技巧(持续更新ing))