前段时间项目需求,需要做一个有限制长度的输入框并动态显示剩余文字,同时也要动态改变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);
}
}
}; }

大致思路就是如此。如有疑问,欢迎加关注联系,相互学习。

demo下载请猛戳

Android 动态改变高度以及计算长度的EditText的更多相关文章

  1. ASPxGridview必须设置ShowVerticalScrollBar为true才能动态改变高度。。。

    ASPxGridview必须设置ShowVerticalScrollBar为true才能动态改变高度... 设置 ShowVerticalScrollBar=true ,这时client-side s ...

  2. android 动态改变listview的内容

    本文模拟:点击一个按钮,为已有的listview添加一行数据 <?xml version="1.0" encoding="utf-8"?> < ...

  3. 【转】Android动态改变对 onCreateDialog话框值 -- 不错不错!!!

    原文网址:http://www.111cn.net/sj/android/46484.htm 使用方法是这样的,Activity.showDialog()激发Activity.onCreateDial ...

  4. android 动态改变控件位置和大小 .

    动态改变控件位置的方法: setPadding()的方法更改布局位置. 如我要把Imageview下移200px:             ImageView.setPadding( ImageVie ...

  5. Android 动态改变布局属性RelativeLayout.LayoutParams.addRule()

    我们知道,在 RelativeLayout 布局中有很多特殊的属性,通常在载入布局之前,在相关的xml文件中进行静态设置即可. 但是,在有些情况下,我们需要动态设置布局的属性,在不同的条件下设置不同的 ...

  6. Android动态改变布局

    遇到这么个需求,先看图:      其实是一个软件的登录界面,初始是第一个图的样子,当软键盘弹出后变为第二个图的样子,因为登录界面有用户名.密码.登录按钮,不这样的话软键盘弹出后会遮住登录按钮(其实之 ...

  7. Android动态改变App在Launcher里面的icon

    如果呆萌的产品童鞋让你动态更换App在Launcher里面的Icon,你怎么回答他,下文就提出一种实现该效果的方法. 原理1--activity-alias 在AndroidMainifest中,有两 ...

  8. android 动态改变屏幕方向

    LANDSCAPE与PORTRAIT 范例说明 要如何通过程序控制Activity的显示方向?在Android中,若要通过程序改变屏幕显示的方向,必须要覆盖 setRequestedOrientati ...

  9. ugui 获取Text的高度,动态改变高度

    项目中需要根据聊天内容的多少.显示外边框的高度.因为Text的内容是不固定的.但宽度是固定的.高度根据文字多少自增 可以通过Text的属性preferredHeight 获取文本框的高度

随机推荐

  1. PatentTips - Supporting address translation in a virtual machine environment

    BACKGROUND A conventional virtual-machine monitor (VMM) typically runs on a computer and presents to ...

  2. opencv之SURF图像匹配

    1.概述 前面介绍模板匹配的时候已经提到模板匹配时一种基于灰度的匹配方法,而基于特征的匹配方法有FAST.SIFT.SURF等.上面两篇文章已经介绍过使用Surf算法进行特征点检測以及使用暴力匹配(B ...

  3. 含有过滤功能的android流式布局

    FilterFlowLayout 含有过滤功能的流式布局, 參考FlowLayout 能够去除宽度不在范围(比例或真实值)内的子view 能够设置最大行数 能够加入组件间水平间距 能够加入行间距 系统 ...

  4. Android Multiple dex files define BuildConfig

    dexOptions { preDexLibraries = false }

  5. openGLES(二)

    顶点和着色器 ​ 我们使用独立的点集合构建物体,都是使用顶点,之后会使用着色绘制图性,以及告诉OpenGLES如何绘制的小程序. ​ 片段着色器,即每个小的像素的渲染, ​ 顶点着色器确定所绘制图像的 ...

  6. python报错Nonetype object is not iterable

    https://www.cnblogs.com/zhaijiahui/p/8391701.html 参考链接:http://blog.csdn.net/dataspark/article/detail ...

  7. 原生js大总结三

    021.定义函数的几种方式   1.关键字函数:function fnName(){};   2.字面量函数:var fn = function(){};   3.构造函数:var fn = new ...

  8. Linux学习总结(4)——Centos6.5使用yum安装mysql——快速上手必备

    第1步.yum安装mysql [root@stonex ~]#  yum -y install mysql-server 安装结果: Installed:     mysql-server.x86_6 ...

  9. AIX上安装Oracle10G软件

    安装准备 (1)确认系统版本号.内核版本号 # oslevel –r   //查看操作系统版本号 //-08能够安装10g,-09能够安装11g watermark/2/text/aHR0cDovL2 ...

  10. 洛谷—— P1091 合唱队形

    https://www.luogu.org/problem/show?pid=1091#sub  ||  http://codevs.cn/problem/1058/ 题目描述 N位同学站成一排,音乐 ...