Android 动态改变高度以及计算长度的EditText
前段时间项目需求,需要做一个有限制长度的输入框并动态显示剩余文字,同时也要动态改变EditText的高度来增加用户体验。现整理出来与大家分享。
先来看看效果图
看了效果就分享一下布局
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="@android:color/black"
tools:context=".MainActivity" > <TextView
android:id="@+id/contentlen"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentRight="true"
android:textColor="@android:color/white"
android:visibility="gone" /> <RelativeLayout
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true" > <FrameLayout
android:id="@+id/send_layout"
android:layout_width="59.0dip"
android:layout_height="wrap_content"
android:layout_alignParentRight="true"
android:layout_centerVertical="true"
android:layout_marginLeft="8.0dip"
android:addStatesFromChildren="true" > <Button
android:id="@+id/send"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:background="@drawable/send_button_normal"
android:minHeight="34.0dip"
android:text="发送"
android:textColor="#ffffff"
android:textSize="14.0sp" />
</FrameLayout> <EditText
android:id="@+id/input"
android:layout_width="fill_parent"
android:layout_height="40dip"
android:layout_alignParentLeft="true"
android:layout_centerVertical="true"
android:layout_marginBottom="8.0dip"
android:layout_marginTop="8.0dip"
android:layout_toLeftOf="@id/send_layout"
android:background="@drawable/input_bg"
android:inputType="textMultiLine"
android:maxLines=""
android:textColor="#000000"
android:textSize="16.0sp" />
</RelativeLayout> </RelativeLayout>
android:layout_alignParentBottom="true"
这句很重要,很多人在第一次做的时候不知道,经常会说弹出的键盘会遮住了输入框,这个加上manifest.xml里的android:configChanges="keyboardHidden|orientation|screenSize"就能可以实现弹出输入法时吧输入框顶上去
<activity
android:name="com.hjhrq1991.myeditdemo.MainActivity"
android:configChanges="keyboardHidden|orientation|screenSize"
android:label="@string/app_name"
android:screenOrientation="portrait"
android:windowSoftInputMode="adjustResize" >
<intent-filter>
<action android:name="android.intent.action.MAIN" /> <category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
这里我使用TextWatcher来对EditText进行监听,动态计算输入的内容。至于取得控件的高度,相信不少新人都是在oncreate方法里使用getHeight方法来取得高度,然后很多人都会抛去一个问题,怎么我取得的值为0?这是因为activity在初始化的时候创建view,而在刚创建view对象时系统并没有绘制完成,因此get出来的高度为0。那么怎么去正确get到高度?应该是在view绘制完成后再去get,是的,监听view的绘制,在view绘制完成后再使用getHeight方法。这里我建议使用ViewTreeObserver方法来监听,再view绘制完成后系统会回调给acitvity通知其绘制完成,而且只执行一次。具体代码如下
package com.hjhrq1991.myeditdemo; import android.os.Bundle;
import android.app.Activity;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.View;
import android.view.ViewTreeObserver;
import android.view.ViewTreeObserver.OnGlobalLayoutListener;
import android.widget.EditText;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast; public class MainActivity extends Activity { private EditText mMsg;//输入框
private TextView mContentLen;//文字长度提示文本 private int mHeight;
private int middleHeight;
private int maxHeight; private boolean lenTips = true; private int MAX_LENGTH = ; @Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main); init();
} /**
* @deprecated 初始化,在这里使用ViewTreeObserver获取控件的高度
*/
private void init() {
mMsg = (EditText) findViewById(R.id.input);
mContentLen = (TextView) findViewById(R.id.contentlen); //动态计算字符串的长度
mMsg.addTextChangedListener(mTextWatcher); //取得控件高度
ViewTreeObserver vto2 = mMsg.getViewTreeObserver();
vto2.addOnGlobalLayoutListener(new OnGlobalLayoutListener() {
@SuppressWarnings("deprecation")
@Override
public void onGlobalLayout() {
mMsg.getViewTreeObserver().removeGlobalOnLayoutListener(this);
mHeight = mMsg.getHeight();
middleHeight = * mHeight / ;
maxHeight = * mHeight / ;
}
});
} /**
* edittext输入监听
*/
TextWatcher mTextWatcher = new TextWatcher() {
private CharSequence temp; // private int editStart;
// private int editEnd;
@Override
public void onTextChanged(CharSequence s, int start, int before,
int count) {
// TODO Auto-generated method stub
temp = s.toString().trim();
} @Override
public void beforeTextChanged(CharSequence s, int start, int count,
int after) {
// TODO Auto-generated method stub
} @Override
public void afterTextChanged(Editable s) {
// TODO Auto-generated method stub
// editStart = mMsg.getSelectionStart();
// editEnd = mMsg.getSelectionEnd();
int len = temp.length();//取得内容长度
int lineCount = mMsg.getLineCount();//取得内容的行数
if (len != ) {
mContentLen.setVisibility(View.VISIBLE);
if (len <= MAX_LENGTH) {
mContentLen.setText("(" + (MAX_LENGTH - temp.length())
+ ")");
} else {
if (lenTips) {
Toast.makeText(
getApplicationContext(),
String.format(
getString(R.string.more_than_litmit),
MAX_LENGTH), ).show();
lenTips = false;
}
mContentLen.setText("(-" + (temp.length() - MAX_LENGTH)
+ ")");
}
} else {
mContentLen.setVisibility(View.GONE);
}
/**
* 根据行数动态计算输入框的高度
*/
RelativeLayout.LayoutParams params = (RelativeLayout.LayoutParams) mMsg
.getLayoutParams();
if (lineCount <= ) {
params.height = mHeight;
mMsg.setLayoutParams(params);
} else if (lineCount == ) {
params.height = middleHeight;
mMsg.setLayoutParams(params);
} else {
params.height = maxHeight;
mMsg.setLayoutParams(params);
}
}
}; }
大致思路就是如此。如有疑问,欢迎加关注联系,相互学习。
Android 动态改变高度以及计算长度的EditText的更多相关文章
- ASPxGridview必须设置ShowVerticalScrollBar为true才能动态改变高度。。。
ASPxGridview必须设置ShowVerticalScrollBar为true才能动态改变高度... 设置 ShowVerticalScrollBar=true ,这时client-side s ...
- android 动态改变listview的内容
本文模拟:点击一个按钮,为已有的listview添加一行数据 <?xml version="1.0" encoding="utf-8"?> < ...
- 【转】Android动态改变对 onCreateDialog话框值 -- 不错不错!!!
原文网址:http://www.111cn.net/sj/android/46484.htm 使用方法是这样的,Activity.showDialog()激发Activity.onCreateDial ...
- android 动态改变控件位置和大小 .
动态改变控件位置的方法: setPadding()的方法更改布局位置. 如我要把Imageview下移200px: ImageView.setPadding( ImageVie ...
- Android 动态改变布局属性RelativeLayout.LayoutParams.addRule()
我们知道,在 RelativeLayout 布局中有很多特殊的属性,通常在载入布局之前,在相关的xml文件中进行静态设置即可. 但是,在有些情况下,我们需要动态设置布局的属性,在不同的条件下设置不同的 ...
- Android动态改变布局
遇到这么个需求,先看图: 其实是一个软件的登录界面,初始是第一个图的样子,当软键盘弹出后变为第二个图的样子,因为登录界面有用户名.密码.登录按钮,不这样的话软键盘弹出后会遮住登录按钮(其实之 ...
- Android动态改变App在Launcher里面的icon
如果呆萌的产品童鞋让你动态更换App在Launcher里面的Icon,你怎么回答他,下文就提出一种实现该效果的方法. 原理1--activity-alias 在AndroidMainifest中,有两 ...
- android 动态改变屏幕方向
LANDSCAPE与PORTRAIT 范例说明 要如何通过程序控制Activity的显示方向?在Android中,若要通过程序改变屏幕显示的方向,必须要覆盖 setRequestedOrientati ...
- ugui 获取Text的高度,动态改变高度
项目中需要根据聊天内容的多少.显示外边框的高度.因为Text的内容是不固定的.但宽度是固定的.高度根据文字多少自增 可以通过Text的属性preferredHeight 获取文本框的高度
随机推荐
- python3输出range序列
b=range(3) #输出的是[0, 1, 2] ,其实这里如果用在循环上,代表着循环多少次,这里是循环3次.从零开始.print(list(b))
- setAttribute的浏览器兼容性
1.element要用getElementById 或者是ByTagName来得到 2.setAttribute("class", vName)中class是指改变"cl ...
- ActiveX控件开发 C#
转自:http://hi.baidu.com/charlesx_kst/item/9c2f42e2920db3f42b09a4ff 前言: 这段时间因为工作的需要,研究了一下ActiveX控件.总结如 ...
- 【习题 6-7 UVA - 804】Petri Net Simulation
[链接] 我是链接,点我呀:) [题意] 在这里输入题意 [题解] 模拟就好 [代码] /* 1.Shoud it use long long ? 2.Have you ever test sever ...
- 【JAVASE】Java同一时候抛出多个异常
Java有异常抛出后.跳出程序.一般无法运行接下来的代码. 大家做登陆功能.常常会实username和password的登陆校验,username或者password错误.假设通常是提示usernam ...
- JS学习笔记 - fgm练习 - 输入数字求和 正则replace onkeyup事件
<style> body{font-size: 12px;} .outer{ width: 500px; margin: 0 auto; } span{ color: #999; } in ...
- struts2_7_Action类中方法的动态调用
(一)直接调用方法(不推荐使用) 1)Action类: private String savePath; public String getSavePath() { return savePath; ...
- 硬件——STM32 , SN74HC573锁存器
74HC573是一款高速CMOS器件: 上图中:输出使能为:OE 锁存使能为:LE 典型电路: 上图中:PWR-AL-0,PWR-AL-1,PWR-AL-2:是单片机输出的高低电平给573 对应的 ...
- sprinng in action 第四版第六章中的ValidationMessages.properties不起作用
文件名必须是ValidationMessages.properties,必须放在类的根目录下
- Web网站架构演变—高并发、大数据
转 Web网站架构演变—高并发.大数据 2018年07月25日 17:27:22 gis_morningsun 阅读数:599 前言 我们以javaweb为例,来搭建一个简单的电商系统,看看这个系 ...