前段时间项目需求,需要做一个有限制长度的输入框并动态显示剩余文字,同时也要动态改变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. Catch Me If You ... Can't Do Otherwise--转载

    原文地址:https://dzone.com/articles/catch-me-if-you-cant-do-otherwise I don't know whether it's an anti- ...

  2. BZOJ2716: [Violet 3]天使玩偶(KD-Tree)

    Description Input Output Sample Input 100 100 81 23 27 16 52 58 44 24 25 95 34 2 96 25 8 14 97 50 97 ...

  3. ListCtrl添加右键菜单(在对话框类中)

    在对话框类中如何添加NM_RCLICK消息: ListCtrl控件右键单击选择属性 在右侧属性栏中选择控件事件 在控件事件中找到NM_RCLICK并添加 完成,写代码

  4. Writing buffer overflow exploits - a tutorial for beginners

    Buffer overflows in user input dependent buffers have become one of the biggest security hazards on ...

  5. 几个经常使用的cmd命令

    compmgmt.msc 计算机管理  devmgmt.msc 设备管理器  diskmgmt.msc 磁盘管理工具  dfrg.msc 磁盘碎片整理  eventvwr.msc 事件查看器  fsm ...

  6. Android学习笔记之ViewFlipper

    <1>被添加到ViewFlipper中的两个或两个以上的视图之间将执行一个简单的ViewAnimator动画.一次仅能显示一个子视图.如果需要,可以设置间隔时间使子视图像幻灯片一样自动显示 ...

  7. 9. ZooKeeper之搭建单机模式。

    转自:https://blog.csdn.net/en_joker/article/details/78673456 在集群和单机两种模式下,我们基本完成了分别针对生产环境和开发环境ZooKeeper ...

  8. Linux常用运维命令小结

    1. 空设备文件以及标准输入输出 /dev/null 表示空设备文件 0 表示stdin标准输入 1 表示stdout标准输出 2 表示stderr标准错误 2>&1 这里有两种解释:将 ...

  9. 你真得懂Javascript中的==等于运算符吗?

    var i = 2; Number.prototype.valueOf = function() { return i++; }; var a = new Number( 42 ); if (a == ...

  10. php课程 11-37 类和对象的关系是什么

    php课程 11-37 类和对象的关系是什么 一.总结 一句话总结:类生成对象,对象是类的实例化,一定是先有类,后有对象,一定是先有标准,再有个体. 1.oop的三大优势是什么? 重用性,灵活性.扩展 ...